웹, 모바일에 최적화된 swiper를 붙일 때 정말 유용한 module인 Swiper.JS

https://swiperjs.com/

 

Swiper - The Most Modern Mobile Touch Slider

Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.

swiperjs.com

 

기본적인 사용법은 문서가 정말 잘 되어있어 평범한 문제 해결은 공식문서로도 충분하다.

 

 

하지만, Swiper Component prop 밖에서 swiper의 methods나 properties를 사용해야만 하는 때도 있지만(e.g., query정보에 맞게 active slide 변경 등), 공식문서에는 이 문제를 해결하기 위한 설명이 없다.

 

React에서  Swiper Component prop 밖에서 swiper의 methods나 properties를 사용하기 위한 방법은 아래 코드를 참고.


const SwiperTest = () => {

	const [swiper, setSwiper] = useState(null);
	const location = useLocation()

	useEffect(()=>{
    	// 새로고침 시 swiper의 값은 default value인 null이므로 if 사용
        if (swiper) {
            swiper.slideTo(activeIndex) // 예시
        }
    },[location.search])
    
    return (
    	<Swiper
        // state인 'swiper'에 Swiper Component instance assign
         onSwiper = {setSwiper} 
         ...
        >
        	<SwiperSlide>text</SwiperSlide>
            ...
        </Swiper>
    )
}

 

+ Recent posts