简体   繁体   中英

Update swiper effect with swiperjs react

I'm looking for a way to update the swiper's effect (and some other settings). I found out that we have to swiper.destroy(true, true) then init the swiper again (from here and here ). Initializing the swiper like one here

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

return Swiper is not a constructor error as I supposed from my imported Swiper is from 'swiper/react' instead of just from 'swiper'. Any ideas how to fix this? or any other approaches?

Thanks!

You will have to import Swiper, I would recommend storing it in a ref that way you're not constantly creating a new instance of Swiper on each render, you can do something like the following:

import Swiper from 'swiper';

const MyComponent = () => {
 const swiperRef = useRef(null);

 useEffect(() => {
    swiperRef.current = new Swiper(
        '.swiper-container', // You can also use a ref to the element here
        {
          loop: true,
          slidesPerView: '2',
          centeredSlides: true,
          pagination: {
            el: '.swiper-pagination',
            clickable: true,
          },
        },
    );

    return () => {
      swiperRef.current.destroy(true, true);
    };
  }, []);

  return (
    ...
  )
}

You can now access swiper using swiperRef.current

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM