OiO.lk Blog javascript How to go to the First slide when reaching the last slide?
javascript

How to go to the First slide when reaching the last slide?


I have this slider that works just fine. However, when it reaches the last slide I want it to keep moving to the RIGHT and show SLIDE 1. My issue is that once it reaches the last slide it moves to SLIDE 1 but it moves to the LEFT. Can anyone point me in the right direction, please? Thanks a lot in advance!

Here’s my LIVE DEMO: https://stackblitz.com/edit/react-ubg8sg?file=src%2FApp.js,src%2Fassets%2Fdata.js,src%2Fstyle.css,src%2Findex.css,src%2Findex.js

Here’s my function that handles the scrolling:

    const scrollToImage = (direction) => {
    if (direction === 'prev') {
      setCurrentIndex((curr) => {
        const isFirstSlide = currentIndex === 0;
        return isFirstSlide ? 0 : curr - 1;
      });
    } else {
      const isLastSlide = currentIndex === data.length - 1;
      if (!isLastSlide) {
        setCurrentIndex((curr) => curr + 1);
      } else {
        setCurrentIndex(0);
      }
    }
  };



You need to sign in to view this answers

Exit mobile version