Home > Enterprise >  Autoplay Slider
Autoplay Slider

Time:11-22

I'd like to add autoplay to my slider, but I don't know how to do it (slider works fine). I understand that it can be done using an interval but I don't handle it very well... If you can give me a hand I would be very grateful

const ImageSlider = ({ slides }) => {
  const [current, setCurrent] = useState(0);
  const length = slides.length;

  const nextSlide = () => {
    setCurrent(current === length - 1 ? 0 : current   1);
  };

  const prevSlide = () => {
    setCurrent(current === 0 ? length - 1 : current - 1);
  };

  const moveDot = (index) => {
    setCurrent(index);
  };

  if (!Array.isArray(slides) || slides.length <= 0) {
    return null;
  }

  return (
    <div className="container-slider">
      Code...
    </div>
  );
};

export default ImageSlider;

CodePudding user response:

useEffect(() => {
  const i = setInterval(() => {
    nextSlide();
  }, 5000);
  return () => {
    clearInterval(i);
  };
}, [current]);

CodePudding user response:

**Use "react-bootstrap/Carousel"** 

import Carousel from "react-bootstrap/Carousel";
import "bootstrap/dist/css/bootstrap.css";
function CarouselIntervalsExample() {
  return (
    <div style={{ display: "block", width: 700, padding: 30 }}>
      <Carousel>
        <Carousel.Item interval={1500}>
          <img className="d-block w-100" src="image1.png" />
          <Carousel.Caption>
            <h3>first slide</h3>
            <p>Image One</p>
          </Carousel.Caption>
        </Carousel.Item>
        <Carousel.Item interval={500}>
          <img className="d-block w-100" src="image2.png" />
          <Carousel.Caption>
            <h3>Label for second slide</h3>
            <p>Image Two</p>
          </Carousel.Caption>
        </Carousel.Item>
      </Carousel>
    </div>
  );
}

export default CarouselIntervalsExample;
  • Related