Create a Masonry Image Gallery Layout with React

sandra gonzales
2 min readAug 20, 2018

--

I wanted a beautiful way to display images in a masonry style layout using a React component that integrated well into my React app, so I came up with react-photo-gallery. It’s very easy to use and customizable. It works responsively, calculating the aspect ratio of your images, to display them in appropriate sized rows or columns.

The Gallery takes as it’s only required prop a list of image objects. Inside that object there are 3 required properties: src, width, height. The reason a width and height is needed for each image is to calculate the aspect ratio and create the layout before having to wait for your images to load. It makes for much faster “time to interaction”. I have found that most APIs return height and width of images, so it’s not usually a problem. One thing to note is the width and height properties are solely used to calculate the aspect ratio and not used for the actual height and width of your image within the gallery.

Columns will changed depending the “columns” prop which the user can change in their own app, but the library provides default ones as well. To detect the size of the Gallery I’m using a polyfill for ResizeObserver.

By default the images are in a row based grid masonry layout but you can change thedirection prop to equal column. Here’s examples of both row and grid based masonry layouts.

Default row based:

Or column based:

For more information on how to use the component visit the docs!

--

--