How to move to slide in swiper.js and react

Viewed 3930

I'm using swiper.js library in my react app. I want to use slideTo method form swiper API but I don't know how can I do that.

Link to not working demo from swiper website

My code

const swiperRef = useRef(null)
useEffect(() => {
  //...some logic
  //if() {
    swiperRef.current.slideTo(0);
  //}
}

return(
  <Swiper pagination={true} navigation={true} ref={swiperRef}>
)

TypeError: swiperRef.current.slideTo is not a function

2 Answers
  1. Add onSwiper to Swiper component
<Swiper
  pagination={true}
  navigation={true}
  onSwiper={(swiper) => setSwiper(swiper)}
>
  1. Add state from swiper
  const [swiper, setSwiper] = useState<Swiper>();
  1. Call this part of code
  swiper.slideTo(0)

replace

swiperRef.current.slideTo(0);

with

swiperRef.current.swiper.slideTo(0);

swiperRef.current is just referencing to the HTML element which does not contain the js function slideTo().

Related