Swiper 사용하여 슬라이드 구현하기(React)

김용희·2024년 5월 10일

[project] Art Friendly

목록 보기
14/14

시작하기

$ npm install swiper
import { Pagination, Scrollbar, Autoplay } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';

import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
  • 스와이퍼 라이브러리와 사용할 모듈을 import 합니다.
  • 주의할 점은 특정 모듈은 css도 함께 import 해야 정상적으로 작동합니다.

예제 코드

const PosterSwiper = ({ posters }: posterSwiper) => {
  return (
    <Swiper
      className="bannerSwiper"
      modules={[Pagination, Scrollbar, Autoplay]}
      spaceBetween={10}
	  // 슬라이드 간의 너비 설정

      slidesPerView={1}
	  // 하나의 슬라이드에 몇 개의 콘텐츠를 보여줄지 설정

      pagination={{ clickable: false }}
      // 페이지네이션 관련 설정
      
      scrollbar={{ draggable: true, hide: true }}
      // 스크롤 관련 설정
      // draggable은 마우스 드래그나 모바일 터치로 슬라이드를 넘길 수 있게 합니다.
      autoplay={{
        delay: 3000,
        disableOnInteraction: false,
      }}
      // 자동으로 슬라이드 넘기기 설정
      
      loop={true}
	  // 마지막 슬라이드에서 슬라이드가 넘어가면 다시 처음으로 갈지 설정
    >
      {posters.map((poster) => (
        <SwiperSlide key={poster.id}>
          <Poster />
        </SwiperSlide>
      ))}
    </Swiper>
  );
};
  • 슬라이드를 적용할 곳을 Swiper 컴포넌트로 감싸고 각각의 슬라이드를 SwiperSlide 컴포넌트로 감싸면 됩니다.
  • 주의할 점은 디자인 커스텀의 경우 CSS로 변경해야 적용됩니다.
.swiper-pagination-bullet {
  width: 10px;
  height: 10px;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  opacity: 0.8;
  background: #d9d9d9;
}

.swiper-pagination-bullet-active {
  color: #fff;
  background: #ff955a;
}

.bannerSwiper {
  width: 100%;
  height: 100%;
}
  • .swiper-pagination-bullet, .swiper-pagination-bullet-active 처럼 기본적으로 부여된 class도 있고 .bannerSwiper처럼 직접 class를 지정하여 커스텀해도 됩니다.

0개의 댓글