How to Use React Image Lightbox

Bri Turner
The Startup
Published in
3 min readAug 3, 2020
Photo by Brigitta Schneiter on Unsplash

In a recent project of mine I decided to add a ‘lightbox’ that allows users to zoom in on and click through images, and rather than creating all of that code from scratch, I turned to React Image Lightbox.

On its Readme, RIL is described as a ‘flexible lightbox component for displaying images in a React project’. It comes prepackaged with all the standard features of a lightbox, and it’s also mobile-friendly with a pinch-to-zoom feature.

In this tutorial I’ll go through the process of installing React Image Lightbox and show you step-by-step how to build your lightbox component.

Adding React Image Lightbox to Your Project

Installing RIL is straightforward. Simply use npm:

$ npm install react-image-lightbox

Now that you’ve got RIL installed we can start creating our lightbox. First you need to add the custom CSS that comes with RIL to your project. Import it into the top of your App.js file:

// in App.js
import 'react-image-lightbox/style.css';

Building the Lightbox File

Now we’ll set up the file that holds our lightbox — my file is called Photos.js.

First, we’ll import the Lightbox component from ‘react-image-lightbox’ and add the URLs of our images. To add the URLs create a const (outside of the class) called ‘images’ that is equal to an array of your image URLs:

Next we’ll add the constructor for our class. We’ll have two things in our state: ‘photoIndex’ and ‘isOpen’.

Now that our state is set up, we’ll create two constants that match our state inside of the render block:

Next we’ll fill out the return block for our page. My page consists of a heading and three rows of pictures.

First, you’ll notice that on each of my images I have an ‘onClick’ function. This opens the lightbox and sets the starting image to whichever image was clicked.

My component is styled using a custom Bootstrap class to create a 3x3 grid. I also have 9 pictures in my ‘images’ array, one for each square on the grid, so you’ll have to update the photoIndex in your onClick function to match which image in the array you want to open on click.

Second, you’ll notice the Javascript that makes RIL function; this is placed just below the closing div tag in the return statement. This code is straight from the RIL example page, and it’s what makes the lightbox function. For my project I didn’t have to modify it at all to get the functionality I was looking for, which is what makes RIL so great.

The resulting lightbox

After all that your lightbox should be up and running! You can sift through photos using either your keypad or the arrows on the lightbox. To close the lightbox just click off of the photo.

Thanks for reading!

--

--