Ziad Alzarka
Posted on November 20, 2020
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
Masonry
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%;
}
Masonry React component
import Masonry from "react-responsive-masonry"
...
<Masonry columnsCount={3} gutter={4}>
{images.map((image) => (
<img src={image} />
))}
</Masonry>
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>
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!
Posted on November 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 29, 2022