React Hooks Masonry
Now that we have React Hooks, so many components can be rewritten in a more succinct, readable and maintainable manner.
🔥 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.
The styled components
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)" />.
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.
More concretely, the above colored tiles are rendered by the this component.