React Hooks Masonry

Now that we have React Hooks, so many components can be rewritten in a more succinct, readable and maintainable manner.

Profile picture
๐Ÿ‘‹
Developed and Written by: Donald Boulton๐ŸŽ‰ 0
|
2019-03-25
1 min read

React Hooks Masonry

๐Ÿ”— janosh.io React Hooks Masonry

๐Ÿ”ฅ Now that we have React Hooks, so many components can (and probably should ๐Ÿ”— despite what Dan said at React Conf) be rewritten in a more succinct, readable and maintainable manner. A perfect candidate for this in my own code base was a Masonry component that used to rely on CSS grid with very narrow rows and managing the number of rows each child item spans based on its natural height to control their placement. With hooks, it was easy to significantly improve on this approach.

For those unfamiliar with โ€œmasonryโ€ on the web, the goal is to create a layout like this.

The new implementation uses only 36 lines of codes and is about as plug-and-play as components get.

src/components/masonry.jsx
jsx

Hooks useEventListener

src/hooks/useEventListener.jsx
jsx

The styled components MasonryDiv and Col each create a CSS grid to space out child items according a default gap 1em or whatever distance in CSS units you pass as a string to <Masonry gap="calc(1vw + 20px)" />.

src/styled/styled.jsx
jsx

Examples

Using Masonry is as simple as wrapping it around an array of child elements. For example, hereโ€™s how youโ€™d use it to display a ๐Ÿ”— list of image thumbnails in a masonry layout.

src/components/masonry.jsx
jsx

ColorBox

More concretely, the above colored tiles are rendered by the this component.

src/components/colorbox.jsx
jsx
Thats it folks!