How to create an image lightbox with Zoom In and Zoom Out functionality in ReactJS ?
Last Updated :
20 Nov, 2023
In this article, we will learn how 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.
Prerequisites:
Steps to Create the React app and Installing the required modules:
Step 1: Create the React app:
npx create-react-app myapp
Step 2: We will install a dependency using npm named react-image-lightbox:
npm i react-image-lightbox
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-image-lightbox": "^5.1.4",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: We will be adding a lightbox component to a React application. Using the useState hook, you manage two states: `showModal` and `indexOfImages` to track the current image index. Clicking a button sets `showModal` to true, rendering the LightBox component.
Javascript
import React, { useState } from "react" ;
import Lightbox from "react-image-lightbox" ;
import "react-image-lightbox/style.css" ;
const arrOfImages = [
];
function App() {
const [indexOfImages, setIndexOfImages] = useState(0);
const [showModal, setShowModal] = useState( false );
const openModalAndSetIndex = (index) => {
setIndexOfImages(index);
setShowModal( true );
return ;
};
return (
<div className= "App" >
<h1>Image Slide Show With Zoom In/Out feature</h1>
{arrOfImages.map((image, index) => (
<img
key={image}
style=
{
{
height: "200px" ,
width: "300px" , margin: "20px"
}
}
src={image}
alt={image}
onClick={() => openModalAndSetIndex(index)}
/>
))}
<div>
<button type= "button"
onClick={() => setShowModal( true )}>
Show Lightbox
</button>
</div>
{showModal && (
<Lightbox
mainSrc=
{arrOfImages[indexOfImages]}
nextSrc=
{arrOfImages[(indexOfImages + 1)
% arrOfImages.length]}
prevSrc={
arrOfImages[
(indexOfImages + arrOfImages.length - 1)
% arrOfImages.length
]
}
onCloseRequest={() => setShowModal( false )}
onMovePrevRequest={() =>
setIndexOfImages(
(indexOfImages + arrOfImages.length - 1)
% arrOfImages.length
)
}
onMoveNextRequest={() =>
setIndexOfImages(
(indexOfImages + arrOfImages.length + 1)
% arrOfImages.length
)
}
/>
)}
</div>
);
}
export default App;
|
Step to run the App:
npm start
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...