13 - Dynamic Image Gallery with Lightbox
Description
Create a React application that displays a dynamic image gallery with a lightbox feature. The gallery should display a grid of image thumbnails, and when a thumbnail is clicked, the corresponding image should be displayed in a lightbox.
Algorithm
Initialize state variables to store the images data and the currently selected image.
Render a grid of image thumbnails using a mapping function.
Define a function to handle image selection and update the selected image state.
Render a lightbox component with the selected image.
Define a function to handle lightbox closing and update the selected image state.
Classes
ImageGallery
: A component that manages the images state and renders the gallery and lightbox.Lightbox
: A component that displays the selected image in a full-screen view.
Code
ImageGallery.js
import React, { useState } from 'react';
import Lightbox from './Lightbox';
function ImageGallery() {
const [images, setImages] = useState([
{ id: 1, url: 'image1.jpg' },
{ id: 2, url: 'image2.jpg' },
{ id: 3, url: 'image3.jpg' },
]);
const [selectedImage, setSelectedImage] = useState(null);
const handleImageSelect = (image) => {
setSelectedImage(image);
};
const handleLightboxClose = () => {
setSelectedImage(null);
};
return (
<div>
<ul>
{images.map((image) => (
<li key={image.id}>
<img
src={image.url}
alt={image.url}
onClick={() => handleImageSelect(image)}
/>
</li>
))}
</ul>
{selectedImage && (
<Lightbox
image={selectedImage}
onClose={handleLightboxClose}
/>
)}
</div>
);
}
export default ImageGallery;
Lightbox.js
import React from 'react';
function Lightbox({ image, onClose }) {
return (
<div className="lightbox">
<img src={image.url} alt={image.url} />
<button onClick={onClose}>Close</button>
</div>
);
}
export default Lightbox;
index.css
.lightbox {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
justify-content: center;
align-items: center;
}
.lightbox img {
max-width: 100%;
max-height: 100%;
}
.lightbox button {
position: absolute;
top: 10px;
right: 10px;
background-color: #fff;
border: none;
padding: 10px;
cursor: pointer;
}
Explanation
The ImageGallery
component initializes the images state and renders a grid of thumbnails. When a thumbnail is clicked, it updates the selected image state and renders the Lightbox
component. The Lightbox
component displays the selected image in a full-screen view and provides a close button to update the selected image state.
Possible Future Enhancements
Add image captions and descriptions.
Implement image zoom and pan functionality.
Add a loading indicator for images.
Integrate with a backend service to fetch images data.
Display image metadata (e.g., camera model, aperture).
Last updated