- Published on
Next.js Masonry Image Galleries
This is a work-in-progress blog post that will chronicle my experiences creating image galleries using Next.js and React. As an example of what I've built so far, you can check out my photos page.
Primary Features
- Responsive images that load different images depending on the user's browser size with blurred placeholders
- Masonry-like image organization that places images in a grid ideally without any gaps
- Lightbox for image zooming
- Keyboard and screenreader accessibility
- Extra effects like image zoom on hover
Technical Approach
For responsive images and blurred image placeholders, I used the Next.js <Image>
component. In order to organize the images into aesthetically pleasing grids with no gaps, I used a library that I previously used in my older site called perfect-layout in which the author Andrea Moretti uses a greedy linear partition algorithm with a BST. The end result is that for most layouts, the grids appear balanced and the execution is performant.
Before using perfect-layout, I experimented using only CSS but found that sometimes there would be gaps / white space for certain layouts.
Next, in order to implement the lightboxes, I used Photoswipe, which provided excellent out of the box keyboard accessibility.
Current Issues
A known issue I'm still working on right now is that image placeholders are not sized correctly on the initial load so users may see images before they are placed into their layout.