Adam Young
Adam Young

Reputation: 31

Swiper JS / React - is it possible to change the current slide depending on some variable

I'm trying to bind a slider to a timer so that the slides automatically change depending on the num parameter. For example num > 0 && num < 1000 will automatically change to the first slide. I tried to do it with swiper.slideTo but the method doesn't work without page reload. Thanks in advance for any help.

Here is some code from my-app:

I managed to change the num value through the slider

  const getIndex = (index) => {
    switch (index) {
      case 0:
        setNum(-2000);
        break;
      case 1:
        setNum(-1000);
        break;
      case 2:
        setNum(500);
        break;
      case 3:
        setNum(2000);
        break;
      default:
        break;
    }
  };

with onSlideChange method

        <Swiper
          spaceBetween={1}
          slidesPerView={1}
          onSlideChange={(e) => getIndex(e.realIndex)}
          navigation
          style={{
            height: '100%',
            width: '100%',
          }}
        >
          {arr.map((item, index) => (
            <SwiperSlide style={{ backgroundColor: item }} key={index}>
              <h1>Slide {index + 1}</h1>
            </SwiperSlide>
          ))}
        </Swiper>

now i am trying to automatically change slide based on num variable

Upvotes: 0

Views: 3962

Answers (1)

Adam Young
Adam Young

Reputation: 31

managed how to do it with useRef and useEffect hooks

const sliderRef = useRef();
const [myIndex, setMyIndex] = useState(0);

  useEffect(() => {
    if (num >= -2000 && num < -1000 && myIndex !== 0) {
      setMyIndex(0);
    }
    if (num >= -1000 && num < 500 && myIndex !== 1) {
      setMyIndex(1);
    }
    if (num >= 500 && num < 2000 && myIndex !== 2) {
      setMyIndex(2);
    }
    if (num >= 2000 && myIndex !== 3) {
      setMyIndex(3);
    }
  }, [num, myIndex]);

  useEffect(() => {
    sliderRef.current.swiper.slideTo(myIndex);
  }, [myIndex]);
<Swiper
          ref={sliderRef}
          spaceBetween={1}
          slidesPerView={1}
          onSlideChange={(e) => getIndex(e.realIndex)}
          navigation
          style={{
            height: '100%',
            width: '100%',
          }}
        >
          {arr.map((item, index) => (
            <SwiperSlide style={{ backgroundColor: item }} key={index}>
              <h1>Slide {index + 1}</h1>
            </SwiperSlide>
          ))}
 </Swiper>

Upvotes: 3

Related Questions