Swiper: Add documentation for initializing Swiper using React hooks

Created on 24 Feb 2020  路  2Comments  路  Source: nolimits4web/swiper

This is a:

  • [x] enhancement
  • Swiper Version: 8.0.0.
  • Platform/Target and Browser Versions: CHROME

What you did

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

Expected Behavior

Should be initialized Correctly.

Actual Behavior

Giving warning and not initializing correctly.

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.

Most helpful comment

 const swiperReference = useRef(null);

  useLayoutEffect(() => {
    swiperReference.current = new Swiper(swiperContainerRef.current, {
      // parameters
    });
  }, []);

  console.log(swiperReference.current);   // access to the swiper instance

All 2 comments

 const swiperReference = useRef(null);

  useLayoutEffect(() => {
    swiperReference.current = new Swiper(swiperContainerRef.current, {
      // parameters
    });
  }, []);

  console.log(swiperReference.current);   // access to the swiper instance

Closing as not related to Swiper itself

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fregiese picture fregiese  路  17Comments

ockle picture ockle  路  18Comments

brandonce picture brandonce  路  19Comments

ginkosen picture ginkosen  路  21Comments

ertdfgcvb picture ertdfgcvb  路  25Comments