How to make carousel auto change instead of click onclick with loop on ReactJs

Viewed 460

I am try to use this carousel ways for my banner. How do I make it auto change without click on the left right button. Due to there is only 2 image how do i make it loop?

import React, { useState } from "react";
import "./Carousel.css";
import { images } from "../Helpers/CarouselData";


function Carousel() {
  const [currImg, setCurrImg] = useState(0);

  return (
    <div className="carousel">
      <div
        className="carouselInner"
        style={{ backgroundImage: `url(${images[currImg].img})` }}
      >
        <div
          className="left"
          onClick={() => {
            currImg > 0 && setCurrImg(currImg - 1);
          }}
        >
          
        </div>
        <div className="center">
          <h1>{images[currImg].title}</h1>
          <p>{images[currImg].subtitle}</p>
        </div>
        <div
          className="right"
          onClick={() => {
            currImg < images.length - 1 && setCurrImg(currImg + 1);
          }}
        >
          
        </div>
      </div>
    </div>
  );
}

export default Carousel;
1 Answers

You can set an interval to run it in your background, changing the currImg. The code below assume you have 2 slides. If you have more slide, you can customize it.

useEffect(()=> {
   const changeSlide = setInterval(() => setCurrImg(prevState => 1-prevState) , 1000) // change your switch time here.
   return () => clearInterval(changeSlide);
}, [])
Related