cedricdelpoux / react-responsive-masonry

React responsive masonry component built with css flexbox
https://cedricdelpoux.github.io/react-responsive-masonry/
MIT License
353 stars 35 forks source link

Add inner window width as default #112

Closed artemijkurganov closed 5 months ago

artemijkurganov commented 10 months ago

Hey there,

We ran into an issue with the MasonryResponsive component when using Scroll Restoration in react-router-dom. The problem was that Scroll Restoration's useLayoutEffect was triggered before useWindowWidth could calculate the width properly. Since MasonryResponsive uses the width to calculate columns, and columns affect the height, this was causing a conflict.

Here's the fix:

Before:

const [width, setWidth] = useState(0)

After:

const [width, setWidth] = useState(window.innerWidth)

Why This Works

Scroll Restoration relies on the window height and was running its useLayoutEffect before MasonryResponsive had the chance to properly calculate the window's width. When the width was stuck at 0, it affected the calculated columns, and as a result, the overall height. This was causing Scroll Restoration to not work correctly.

By making sure the window's width is always properly returned, the columns and consequently the height are calculated accurately. This allows MasonryResponsive to function smoothly alongside Scroll Restoration, even if Scroll Restoration's useLayoutEffect is triggered first.

Conclusion

This is a straightforward change that ensures MasonryResponsive and Scroll Restoration work well together. It corrects the timing issue between the calculation of window width and Scroll Restoration's useLayoutEffect, making sure everything falls into place nicely.

Please have a look and let me know what you think!

Thanks! 🚀

evilPaprika commented 9 months ago

@cedricdelpoux seems like small and reasonable change

cedricdelpoux commented 5 months ago

Sorry for the delay 😞 It published in 2.2.0. Thank you for your help !