Shofol
Shofol

Reputation: 733

How to initialize Swiper using React hooks?

I am using React hooks and Swiper (SwiperJS Link) library. But, getting an error on initializing it. Can anyone help? I tried like this-

    let mySwiper; 
    useEffect(() => {
    mySwiper = new Swiper('.swiper-container', {
        loop: true,
        slidesPerView: '2',
        centeredSlides: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
    });
})

But, React is giving me this warning and not initializing the slider correctly. The warning-

Assignments to the 'mySwiper' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect.

And, at last, my template-

<div className="swiper-container">
   <div className="swiper-wrapper">
      {
         places.map((item, index) => (
          <div key={index} className="swiper-slide"
            onTouchStart={() => { onPlaceSelect(index) }}
            onTouchCancel={() => { onPlaceSelect(index) }}>
              <Package
                 className="swiper-slide"
                 key={index}
                 backgroundImage={Background}
                 modelImage={Model}
                 title="Learn  traditionally"
                 price="15"
                 ref={myRef.current[index]} />
          </div>))}
   </div>
</div>

So, what is the correct way to initilize it using React hooks?

Upvotes: 1

Views: 9226

Answers (1)

Subin Sebastian
Subin Sebastian

Reputation: 10997

Your useEffect will run in every render, each time creating new Swiper instance. Try storing swiper instance in state and run useEffect only once.

let [mySwiper, setMySwiper] = useState(null) 
useEffect(() => {
  let mySwiper = new Swiper('.swiper-container', {
     loop: true,
     slidesPerView: '2',
     centeredSlides: true,
     pagination: {
        el: '.swiper-pagination',
        clickable: true,
     },
  });
  setMySwiper(mySwiper) 
}, [])

[] as the second param for useEffect makes sure, the effect is run only once, ie during component mount.

Upvotes: 3

Related Questions