Swiper를 React에서 사용해보자

2023. 1. 5. 04:01
반응형

Swiper는 캐러셀 슬라이드를 쉽게 사용할 수 있는 라이브러리다.
하지만 CSS 파일을 import해야 스타일이 입혀지고
다양한 설정값이 있어서 원하는 대로 설정할 수 있으나 동시에 복잡하다는 단점이 있다.

npm i swiper

Swiper를 사용하려면 다음과 같이 작성한다.
공식 문서를 참고하여 자주 사용하는 기능 위주로 작성하였다.

//Swiper컴포넌트와 슬라이드 컴포넌트를 불러온다
import { Swiper, SwiperSlide } from  'swiper/react'
//Swiper의 기본 css
import  'swiper/css'
//navigation과 pagination은 import 해야 그려준다.
import  'swiper/css/navigation'
import  'swiper/css/pagination'
//필요한 모듈을 추가할 수 있다.
import { Pagination, Navigation, Scrollbar, Autoplay } from  'swiper'

const index = () => {

  return (
    <div>
      <Swiper
        modules={[Pagination, Navigation, Autoplay]}
        loop={true} //슬라이드를 무한루프한다
        centeredSlides={true} //슬라이드를 가운데 맞춤한다
        loopAdditionalSlides={1} //루프 시에 슬라이드를 1개 복제한다
        spaceBetween={50} //슬라이드 간 여백(margin-right로 들어간다)
        slidesPerView={3} //한번에 보여주는 슬라이드 수
        slidePerGroup={3} //한번에 넘기는 슬라이드 수
        watchOverflow={true} //슬라이드가 모자라면 네비게이션 등을 감춘다
        navigation
        pagination={{ clickable:  true, type:  'bullets'}}
        scrollbar={{ draggable:  true, el:  null }}
        autoplay={true} //true: 자동재생, true 대신에 delay 값을 넣어 
                        //슬라이드 전환 속도조절을 할 수 있다.
        onSlideChange={() => console.log('slide change')}
        onSwiper={(swiper) => console.log(swiper)}
        breackpoints={{ //반응형을 위해 breakpoint를 기입할 수 있다.
          640: {
            slidesPerView: 1,
            spaceBetween: 10,
          },
          768: {
            slidesPerView: 1,
            spaceBetween: 20,
          },
          1024: {
            slidesPerView: 1,
            spaceBetween: 30,
          },
          1280: {
            slidesPerView: 1,
            spaceBetween: 40,
          }
        }}
      >
        <SwiperSlide>
         //내부에 이미지나 div요소를 넣을 수 있다.
         <div>
           <img src="" alt="슬라이드"/>
         </div>
        </SwiperSilde>
      </Swiper>
    </div>
  )
}

Swiper에는 다양한 모듈을 지원하는데 자주 사용하는 것은 다음과 같다.

  • pagination
    -- 슬라이드가 몇개인지 표시해주고 클릭 시 해당 슬라이드로 이동한다

  • navigation
    -- 슬라이드를 좌우로 이동한다
    -- prevEl

  • autoplay
    -- 슬라이드를 자동으로 실행한다

  • scrollbar
    -- 슬라이드를 좌우로 스크롤한다

    모듈은 상단에 import 하고 Swiper 태그 안에 modules={[ '모듈이름' ]} 으로 기입하여 사용해야 한다. 모듈을 사용할 때도 Swiper 태그 안에 해당 모듈이름과 prop을 작성해야 한다.

디자인을 수정하려면?

  1. 가장 간단한 것은 CSS파일을 수정하는 것이다.
    Swiper는 swiper.bundle.js , swiper.bundle.min.js, swiper.min.js 등의 파일을 가지고 있으므로 해당 경로의 파일 중 하나를 수정해서 import 하면 된다. 많은 인터넷 예제들이 CSS 파일을 직접 수정하여 사용한다.

  2. 두번째로 Swiper 관련 태그에 style={{ width: '100px' }} 과 같은 식으로 인라인 스타일로 작성해주는 것이다. CSS파일보다 우선해서 스타일이 적용되어야 할 경우에 쓸 수 있다.

  3. 만약 emotion이나 twin.macro 같은 css 관련 라이브러리를 사용한다면 css={ } 또는 tw=" " 등으로 값을 줄 수도 있겠지만 swiper와 충돌할 때도 있어서 확인이 필요하다.

네비게이션이나 페이지네이션을 수정하고 싶다면

import { useRef } from 'react'
//... swiper 관련 import는 생략
const prevRef = useRef(null);
const nextRef = useRef(null);
const pageRef = useRef(null);

  <Swiper
    pagination={{ el: pageRef.current }}
    navigation={{ prevEl: prevRef.current, nextEl: nextRef.current }}
    onBeforeInit={(swiper) => {
      swiper.params.navigation.prevEl = prevRef.current;
      swiper.params.navigation.nextEl = nextRef.current;
      swiper.navigation.update();
  >
    <SwiperSlide>Slide1</Swiper>
  </Swiper>
  <div>
    <button type="button" ref={prevRef}> 이전 </button>
    <button type="button" ref={nextRef}> 다음 </button>
  </div>
  <div ref={pageRef}></div>
//... 생략

페이지네이션이나 네비게이션의 위치 혹은 모양을 수정하고 싶을 수 있다.
navigation는 prevEl 과 nextEl 속성이 있어서 해당 속성에 요소를 입력해주면 된다.
위의 예제는 useRef를 사용해서 좌우 버튼에 각기 ref를 걸어주었다.
pagination 또한 el 속성에 작성해주면 된다.
요소의 클래스명을 지정해주어도 렌더링에는 지장이 없으나, 리액트는 클래스 선택자보다 ref 사용을 권장하니, ref를 걸었다.

Swiper를 대체할 수 있는 라이브러리

  1. Slick
    제일 가볍고 간단하게 쓰인다. jquery 의존성이 있어서 꺼려지지만 그럼에도 가장 많이 쓰이는 라이브러리
  2. Owl carousel
    Slick과 유사한 캐러셀 라이브러리
  3. 그 외에는 alice carousel, react-material-carousel, flicker 등이 있다.
반응형

BELATED ARTICLES

more