DEV Community

Cover image for React Image Gallery with Masonry.js
Ziad Alzarka
Ziad Alzarka

Posted on • Originally published at thetuteur.com

React Image Gallery with Masonry.js

Creating a responsive image gallery like Google Photos on the web has always been a mystery to me, but Masonry.js offers a really easy and convenient way to add image galleries to your website whether you are using Vanilla JavaScript or an SPA like React.

Google Photos

google photos

Masonry

masonry example

Masonry is a JavaScript library for the web. It allows you to create beautiful seamless responsive image galleries. We are using a React implementation react-responsive-masonry.

It is a very lightweight library that adds to your bundle 1.5KB of minified and gzipped JavaScript.

React Image Gallery Example

Masonry uses flexbox under the hood which makes it very easy to use and you only need one line of CSS to get it to work.

Make images fit their container



img {
  width: 100%;
}


Enter fullscreen mode Exit fullscreen mode

Masonry React component



import Masonry from "react-responsive-masonry"
...
<Masonry columnsCount={3} gutter={4}>
  {images.map((image) => (
    <img src={image} />
  ))}
</Masonry>


Enter fullscreen mode Exit fullscreen mode

CodePen example

See the Pen React Image Gallery with Masonry.js by Ziad Alzarka
(@ziad-alzarka) on CodePen.

Going Responsive

Masonry is designed to be responsive and it is very easy to add breakpoints to the masonry component.



const columnsCountBreakPoints = { 350: 1, 750: 2, 900: 3 };

<ResponsiveMasonry columnsCountBreakPoints={columnsCountBreakPoints}>
  <Masonry gutter={4}>
    {images.map((image) => (
      <img src={image} />
    ))}
  </Masonry>
</ResponsiveMasonry>


Enter fullscreen mode Exit fullscreen mode

CodePen example

See the Pen React Responsive Image Gallery with Masonry.js by Ziad Alzarka
(@ziad-alzarka) on CodePen.

The article was originally published on my blog here.

Feel free to follow me on Twitter. Hope I could help!

Top comments (1)

Collapse
 
mohdahmad1 profile image
Mohd Ahmad

bottom layout is broken, see

image