paulcollett / react-masonry-css

React Masonry layout component powered by CSS, dependancy free
https://paulcollett.github.io/react-masonry-css/demo/
MIT License
961 stars 66 forks source link

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

Closed ferdinandlist closed 2 years ago

ferdinandlist commented 2 years ago

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 commented 2 years ago

I just realized there is a pull request for this here: https://github.com/paulcollett/react-masonry-css/pull/74 My bad I had not seen it before. I'll check this solution and report back.

ferdinandlist commented 2 years ago

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