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 = [
    "https://example.com/image1.jpg",
    "https://example.com/image2.jpg",
    "https://example.com/image3.jpg"
  ]

  const openLightbox = (index) => {
    setIsOpen(true)
    setSelectedImageIndex(index)
  }

  const closeLightbox = () => {
    setIsOpen(false)
  }

  return (
    <div>
      <h1>My Component</h1>
      {images.map((image, index) => (
        <img
          key={index}
          src={image}
          onClick={() => openLightbox(index)}
        />
      ))}
      {isOpen && (
        <Lightbox
          mainSrc={images[selectedImageIndex]}
          onCloseRequest={closeLightbox}
        />
      )}
    </div>
  )
}

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: https://www.npmjs.com/package/react-18-image-lightbox

Leave a Reply

Your email address will not be published. Required fields are marked *