How to Incorporate a Simple Image Gallery to your React Project
Adding a gallery to your React project doesn’t have to be a chore, and with the power of open source now it’s easier than ever.
React-photo-gallery and react-images
I decided to use react-photo-gallery together with react-images for its simplicity and easy setup, please keep in mind that react-images is not currently maintained and react-responsive-carousel is currently recommended, but if you need a lightweight gallery react-images will fit the bill.
Setting things up
After running:
npm install react-images
npm install react-photo-gallery
or,
yarn add react-images
yarn add react-photo-gallery
to install the packages, you want to make sure you import them at the top of the component that’s going to have access to the gallery. We’ll also import useState, useCallback, render (you can avoid that if not using a functional component,) Gallery, Carousel, Modal, Gateway, and the location of the photos you want to display (stored as a constant.)
import React, { useState, useCallback } from “react”;
import Gallery from “react-photo-gallery”;
import Carousel, { Modal, ModalGateway } from “react-images”;
import { photos } from “./photos”;
for the photos, they’re stored as objects in an array in a constant, I used picsum as placeholders but normally they’d point to a specific url or your local files
export const LookbookSrc = [ { src: 'https://picsum.photos/200/302', width: 4, height: 3 }, { src: 'https://picsum.photos/200/303', width: 1, height: 1 }, { src: 'https://picsum.photos/200/301', width: 4, height: 3 }
]## etc, add as many as you need
let’s set up useState like so,
const [currentImage, setCurrentImage] = useState(0);const [viewerIsOpen, setViewerIsOpen] = useState(false)
and useCallback,
const openLightbox = useCallback((event, { photo, index }) => { setCurrentImage(index) setViewerIsOpen(true)}, [])const closeLightbox = () => { setCurrentImage(0); setViewerIsOpen(false)}
that will control opening the images when you click them, using lightbox to darken the rest of the page and closing them once you click again.
The finished component
Your finished component will look like this, this is an example from my most recent project, salon-template so adjust to your project as necessary
Adding a simple gallery to your react project is super simple and there are a million ways of doing it, happy coding!