본문 바로가기

Programming/React

[React] TypeScript에서 Swiper 사용하기

728x90
// Import Swiper React components
import { Swiper, SwiperSlide } from 'swiper/react';

// Import Swiper styles
import 'swiper/css';

export default () => {
  return (
    <Swiper
      spaceBetween={50}
      slidesPerView={3}
      onSlideChange={() => console.log('slide change')}
      onSwiper={(swiper) => console.log(swiper)}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
      ...
    </Swiper>
  );
};

Swiper에서 가장 기본적으로 사용되는 코드샘플이다.

 

다만 타입스크립트에선 해당 코드를 그대로 사용하면 

 

ERROR in src/components/HashTag/HashTag.tsx:14:18
TS7006: Parameter 'swiper' implicitly has an 'any' type.
    12 |       slidesPerView={3}
    13 |       onSlideChange={() => console.log("slide change")}
  > 14 |       onSwiper={(swiper) => console.log(swiper)}
       |                  ^^^^^^
    15 |     >
    16 |       <SwiperSlide>Slide 1</SwiperSlide>
    17 |       <SwiperSlide>Slide 2</SwiperSlide>

이런 에러가 발생하게된다.

타입스크립트... 너무나 어렵다... 그냥 자바스크립트에서는 아무 문제없이 샘플코드도 작동이 잘 됬는데...

 

에러는 'onSwiper' 의 콜백 함수 부분에서 발생하는데 'swiper' 매개변수의 타입이 명시되지 않았다고 나온다.

 

먼저 'SwiperCore' 를 가져와야 하기에 

 

import { Swiper as SwiperCore } from "swiper"; 를 import 시켜준 후

 

onSwiper 콜백 부분을 onSwiper={(swiper: SwiperCore) => console.log(swiper)} 로 고쳐주면 작동된다!

 

콜백함수를 분명 안쓸 수가 없을테니까... 기록해두기!