본문 바로가기

개발

React에서 Swiper 좌우 이동 method 사용하기 (with Typescript)

👆react에서 swiper 라이브러리를 사용하다가 첫번째 아이템으로 이동시켜야 하는 이슈가 생겼다.

swiper버전 6.7.0
개발 환경 React & typescript
사용한 swiper method slideTo

사용방법은 swiper 공식 문서에 잘 나와있지만

React&typescript환경에서 정확한 Type과 Hook을 사용한 방법을 찾다가 관련 정보가 많지 않은 것 같아 정리 하게 되었다.

https://swiperjs.com/swiper-api#method-swiper-slideTo

 

Swiper API

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

swiperjs.com

 

내가 사용한 코드

const [swiperInstance, setSwiperInstance] = useState<SwiperCore>();

const swiperParams: Swiper = useMemo(
    () => ({
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },
    }),
    [],
  );
  
  // 새로운 리스트가 뿌려질때마다 처음 아이템으로 슬라이딩 되게 처리
  useEffect(() => {
    swiperInstance?.slideTo(0, 0);
  }, [projectId]);
  
  <Swiper {...swiperParams} onSwiper={setSwiperInstance}>
  ...

👍 onSwiper 이벤트 함수를 통하여 SwiperCore타입의 swiper instance를 받을수 있었으며

해당 instance의 sildeTo메소드를 이용하였다.

 

타입스크립트 버전이 아닌 관련글로 정리하려다 코드가 지저분하고 타입도 정의 못할 것 같았으나,

onSwiper 이벤트로 인스턴스를 받을수 있고 SwiperCore타입 정의를 할수 있어 나름 깔끔한 코드로 정리된것 같아 

기쁘다. 😀

 

혹시 더 좋은 방법이 있으면 공유 바랍니다.