Next.js for Image Galleries and Sliders


Introduction

Image galleries and sliders are popular components in web development. With Next.js, you can build interactive and responsive image galleries and sliders with ease. In this tutorial, we will guide you through the process of creating an image gallery and a simple image slider using Next.js.


Setting Up the Project

To get started, make sure you have Node.js and npm installed on your system. If not, you can download and install them from the official website.


Create a new Next.js project using the following commands:


        npx create-next-app image-gallery-app
cd image-gallery-app

Creating the Image Gallery

Let's start by creating an image gallery. We'll organize images into an array and map through them to display in a grid. We'll use the `next/image` component for optimized image loading.


        // pages/gallery.js
import Image from 'next/image';
const images = [
'/image1.jpg',
'/image2.jpg',
'/image3.jpg',
// Add more image paths
];
export default function Gallery() {
return (
<div>
<h2>Image Gallery</h2>
<div className="gallery">
{images.map((image, index) => (
<div key={index} className="gallery-item">
<Image src={image} alt={`Image ${index + 1}`} width={300} height={200} />
</div>
))}
</div>
</div>
);
}

Creating the Image Slider

To build an image slider, we'll create a component that allows users to navigate through images with next and previous buttons.


        // components/ImageSlider.js
import { useState } from 'react';
const images = [
'/image1.jpg',
'/image2.jpg',
'/image3.jpg',
// Add more image paths
];
export default function ImageSlider() {
const [currentImage, setCurrentImage] = useState(0);
const nextImage = () => {
setCurrentImage((currentImage + 1) % images.length);
};
const prevImage = () => {
setCurrentImage((currentImage - 1 + images.length) % images.length);
};
return (
<div className="image-slider">
<button onClick={prevImage}>Previous</button>
<img src={images[currentImage]} alt={`Image ${currentImage + 1}`} />
<button onClick={nextImage}>Next</button>
</div>
);
}

Conclusion

You've learned how to create an image gallery and a simple image slider using Next.js. These are great components to showcase images or products on your website. You can enhance these components by adding features like captions, captions, and transitions.