Skip to content

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

@ferdinandlist

Description

@ferdinandlist

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>
 );

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions