How to use React 18 image lightbox?

react-18-image-lightbox is a library that provides a customizable lightbox component for displaying images. Here are the steps to use react-18-image-lightbox in your React project:

1. Install the library using npm or yarn:

npm install react-18-image-lightbox

// or

yarn add react-18-image-lightbox

2. Import the Lightbox component and any other dependencies you may need, such as images or CSS styles. Here’s an example:

import React, { useState } from "react"
import { Lightbox } from "react-18-image-lightbox"
import "react-18-image-lightbox/style.css"

const MyComponent = () => {
  const [isOpen, setIsOpen] = useState(false)
  const [selectedImageIndex, setSelectedImageIndex] = useState(0)

  const images = [

  const openLightbox = (index) => {

  const closeLightbox = () => {

  return (
      <h1>My Component</h1>
      {, index) => (
          onClick={() => openLightbox(index)}
      {isOpen && (

export default MyComponent

In this example, we’re importing the Lightbox component from react-18-image-lightbox and the default CSS styles. We’re also defining an array of images to display and using the useState hook to manage the state of the lightbox.

3. Add the images you want to display in your component, and add an onClick handler to each image that calls the openLightbox function with the index of the clicked image.

4. In the openLightbox function, set the state of the isOpen and selectedImageIndex variables to true and the index of the clicked image, respectively.

5. In the component’s return statement, render the images and the Lightbox component. If the lightbox is open (isOpen is true), render the Lightbox component with the mainSrc prop set to the URL of the selected image and the onCloseRequest prop set to the closeLightbox function.

That’s it! With these steps, you should be able to use react-18-image-lightbox to display images in a customizable lightbox component in your React project.

More info:

Exit mobile version