Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changing column count calculation to depend on container width instead of window width #88

Closed
ferdinandlist opened this issue Nov 22, 2022 · 2 comments

Comments

@ferdinandlist
Copy link

ferdinandlist commented Nov 22, 2022

Hello, I am using react-masonry-css in a resizable container that may not take up the full width of the window. Consequently reCalculateColumnCoun will deliver unsatisfying results as it is using window.innerWidth to compute the number of columns.

Now fixing that is easy, there can simply be a ref created from the masonry container div and the window.innerWidth be replaced with the width of the container ref.
However, this requires me to wrap reCalculateColumnCount inside componentDidMount into a short setTimeout as supposedly the ref is not ready when the component mounts so the initial column count computation will not receive a correct width value. This workaround is functional but probably not elegant and I was wondering whether anyone has an idea for a better solution regarding the intial mounting because I certainly do not consider this version worth a pull request.

Best
Ferdinand

componentDidMount() {
    setTimeout( () => {
      this.reCalculateColumnCount();
    }, 150 )
}
    
 /* [...] */
    
reCalculateColumnCount() {

    const windowWidth = ( () => {
        if(this.containerRef.current) return this.containerRef.current.clientWidth;
        return Infinity;
    } )();

    /* [...] */

 }
    
 /* [...] */
    
 containerRef = React.createRef();
    
 return (
      <div
        ref={ this.containerRef }
        {...rest}
        className={classNameOutput}
      >
          { this.renderColumns() }
      </div>
 );
@ferdinandlist
Copy link
Author

I just realized there is a pull request for this here: #74
My bad I had not seen it before. I'll check this solution and report back.

@ferdinandlist
Copy link
Author

Pull request #74 does the job just fine. Sorry for the noise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant