How to create an image lightbox with Zoom In and Zoom Out functionality in ReactJS ?
In this article you will learn to create an image lightbox with Zoom In and Zoom Out functionality in React. So let’s get started by installing react using the create-react-app command.
Creating React app and Installing the required modules:
- Creating React app.
npx create-react-app myapp
- Now we will install a dependency using npm named react-image-lightbox,
npm i react-image-lightbox
Project Structure: After doing these installations. Our folder structure would look something like this.
We will be now be working on the App.js File. In this file first, we will import the Lightbox component from “react-image-lightbox”.Now create an empty array. This array will contain the source of images that you want to be displayed in the lightbox. Now in the App function, we will create the UI and all the functionality related to the LightBox. The UI as per this article will be very simple, you can change the UI as per the requirement. The UI will contain a simple button. This button when clicked will trigger the modal for the lightbox to get Open.
Filename- src/App.js The Code for UI is as follows.
Now we will be adding the lightbox component to our react application. The arrOfImages contains the URL to our source images. We will use the useState hook to change the state, One hook will open and close the modal containing the Modal. The other hook will change the index of the main image, When the button has been clicked the state of the showModal changes to true and the LightBox component gets rendered. In the Lightbox toolbar, we will see the buttons to close the modal and also to zoom in or out the main image. Also, two buttons one to slide to the next image and the other to slide to the previous image is there. To show the next image on the button click the index of the current image is changed via the setIndexOfImages function. When the next button has clicked the index of the current image is incremented and when the previous button is pressed the index is decremented.