본문 바로가기

TIL

TIL 23.08.11 React 스와이퍼 구현

바닐라자바스크립트 할때 제일 힘들게 했던건 스와이프 기능 구현하기였다. 힘들게 만든 스와이프 기능도 CORS 에러로 잘 구현이 안됨 🙃리액트는 스와이퍼 라이브러리로 간단하게 스와이프 기능을 구현할 수 있다.

 

 

리액트 스와이퍼 공식문서

 

https://swiperjs.com/react

 

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

 

1. 기능구현에 필요한 스와이퍼 라이브러리 먼저 설치한다.

 

yarn add swiper

 

2. 필요한 모듈을 import 해준다. 나는 Pagination, Autoplay 씀.

 

import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination, Scrollbar, Autoplay } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import 'swiper/css/autoplay';

 

3. 필요에 따라 스와이퍼를 세팅한다.

 

<Swiper
  // 필요한 스와이퍼 모듈 세팅
  modules={[Pagination, Autoplay]}
  spaceBetween={0}
  slidesPerView={1} // 한 화면에 몇개의 요소를 보여줄 것인지
  pagination={{ clickable: true }}
  // onSwiper={(swiper) => console.log(swiper)}
  // onSlideChange={() => console.log('slide change')}
  autoplay={{ delay: 2000 }} // 2초마다 슬라이드 전환
>
  <SwiperSlide>
    슬라이드 1
  </SwiperSlide>
  <SwiperSlide>
    슬라이드 2
  </SwiperSlide>
  <SwiperSlide>
    슬라이드 3
  </SwiperSlide>
</Swiper>;

 

결과

 

리액트 스와이퍼