Open In App

Building a Carousel Component with React Hooks

Building a Carousel Component with React Hooks involves creating a functional component that manages state using useState and useEffect hooks. You can track the current slide index, handle navigation, and update the UI dynamically based on user interactions or timing events. Utilizing hooks like useState for state management and useEffect for side effects simplifies the implementation of a carousel in React.

Output Preview:

Screenshot-2024-04-04-153621

Prerequisites

What are React Hooks?

React Hooks are functions provided by React that allow you to use state and other React features in functional components. They offer a more concise and straightforward way to manage stateful logic, handle side effects, and access React features that were previously only available in class components. With React Hooks, developers can write functional components that are more modular, reusable, and easier to understand compared to class components.

Approach

Steps to Setup the Project

Step 1: Create a reactJS application by using this command

npx create-react-app my-app

Step 2: Navigate to the project directory

cd my-app

Project Structure:

Screenshot-from-2024-03-29-08-15-04

folder strucuture

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "^5.0.0"
},

Example: Implementation to showcase the design of carousel component by using react hooks.

/* Carousel.css */

.carousel-container {
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
}

.carousel {
    position: relative;
    overflow: hidden;
}

.carousel-slide {
    display: none;
    transition: opacity 0.5s ease;
}

.carousel-slide.active-slide {
    display: block;
    opacity: 1;
}

.carousel img {
    width: 100%;
    height: auto;
    object-fit: cover;
}

.carousel-button {
    position: absolute;
    top: 30%;
    transform: translateY(-50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    cursor: pointer;
    padding: 10px;
    font-size: 18px;
    z-index: 1;
}

.carousel-button.prev {
    left: 10px;
}

.carousel-button.next {
    right: 10px;
}

.app-container {
    text-align: center;
}

.app-heading {
    margin-bottom: 20px;
    font-size: 32px;
    color: #333;
}

.carousel-wrapper {
    border: 2px solid #ddd;
    border-radius: 10px;
    overflow: hidden;
}
// Carousel.js

import React, { useState, useEffect } from "react";
import "./Carousel.css";

const Carousel = ({ images }) => {
    const [currentIndex, setCurrentIndex] = useState(0);

    useEffect(() => {
        const interval = setInterval(() => {
            setCurrentIndex((prevIndex) =>
                prevIndex === images.length - 1
                    ? 0
                    : prevIndex + 1
            );
        }, 5000);

        return () => clearInterval(interval);
    }, [images.length]);

    const nextSlide = () => {
        setCurrentIndex((prevIndex) =>
            prevIndex === images.length - 1
                ? 0 :
                prevIndex + 1
        );
    };

    const prevSlide = () => {
        setCurrentIndex((prevIndex) =>
            prevIndex === 0
                ? images.length - 1
                : prevIndex - 1
        );
    };

    return (
        <div className="carousel-container">
            <div className="carousel">
                {images.map((image, index) => (
                    <div
                        key={index}
                        className={
                            index === currentIndex
                                ? "carousel-slide active-slide"
                                : "carousel-slide"
                        }>
                        <img src={image}
                            alt={`Slide ${index + 1}`} />
                    </div>
                ))}
            </div>
            <button className="carousel-button prev"
                onClick={prevSlide}>
                &#10094; Prev
            </button>
            <button className="carousel-button next"
                onClick={nextSlide}>
                Next &#10095;
            </button>
        </div>
    );
};

export default Carousel;
// App.js

import React from "react";
import Carousel from "./Carousel";

const App = () => {
    const images = [
"https://media.geeksforgeeks.org/wp-content/uploads/20210228231058/gfg.png",
"https://media.geeksforgeeks.org/wp-content/uploads/20190809013546/gfg_350X350.png",
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png",
    ];

    return (
        <div className="app-container">
            <h1 className="app-heading">
                React Carousel
            </h1>
            <div className="carousel-wrapper">
                <Carousel images={images} />
            </div>
        </div>
    );
};

export default App;

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: Your project will be shown in the URL http://localhost:3000/

wsa


Article Tags :