Open In App

Building a Carousel Component with React Hooks

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Begin by creating a functional component for the Carousel, importing React and necessary hooks.
  • Apply CSS styles to achieve the desired UI for the carousel, including slide transitions, button positions, and overall layout.
  • Use the useState hook to manage the current index of the carousel. This state will track which image is currently being displayed.
  • We use useEffect to set up an interval that automatically changes the slide every 5 seconds (5000 milliseconds).
  • The useEffect cleanup function clears the interval when the component unmounts or when the images array length changes.
  • Implement functions to handle moving to the next and previous slides by updating the current index state accordingly.
  • Map through the array of images to render each image within the carousel container. Use the current index state to determine the active slide.
  • Attach onClick event handlers to the next and previous buttons to call the respective slide functions when clicked.

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.

CSS
/* 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;
}
JavaScript
// 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;
JavaScript
// 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




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads