swiper 옵션 정리

오찬주·2025년 5월 4일

개발 log

목록 보기
20/23

캐러셀 구현을 위해 종종 swiper를 사용한다.

설치

npm install swiper

파일에서 import해야 할 것들

import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/swiper-bundle.css";

//pagination, Mousewheel, Keyboard를 사용한다면
import { Pagination, Mousewheel, Keyboard } from "swiper/modules";

기본 구성 코드

import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';

<Swiper>
// 슬라이드 할 대상
  <SwiperSlide>Slide 1</SwiperSlide>
  <SwiperSlide>Slide 2</SwiperSlide>
</Swiper>

자주 사용하는 옵션

  • slidesPerView: 한 화면에 보여질 슬라이드 개수
  • spaceBetween: 슬라이드 간 간격 (px 단위)
  • loop: 슬라이드를 무한 반복 (loop={true}
  • autoplay: 자동 재생 (지연 시간 등 조절 가능)
  • pagination: 밑의 dots 설정
  • navigation: 좌우 화살표 설정 (navigation={true})
  • breakpoints: 반응형 설정
breakpoints={{
  640: { slidesPerView: 1 },
  768: { slidesPerView: 2 },
  1024: { slidesPerView: 3 },
}}

*autoplay, pagination, navigation 등은 모듈로 불러와서 사용할 수 있다!

import { Autoplay, Pagination, Navigation } from 'swiper/modules';

<Swiper
  modules={[Autoplay, Pagination, Navigation]}
  ...
>

만약 swiper의 스타일을 변경해주고 싶다면?

import "swiper/swiper-bundle.css";

이렇게 import 해준다 !

실제 사용 예시

주로, 내용들을 불러와서 같은 컴포넌트 들에 내용들을 넣고 슬라이드를 하게 된다. 그렇게 되면 예시 코드는 다음과 같다!

   <Swiper
        modules={[Pagination, Mousewheel, Keyboard]}
        spaceBetween={16}
        slidesPerView={1}
        pagination={{ clickable: true }}
        mousewheel={true}
        keyboard={true}
        onSlideChange={handleSlideChange}
        onSwiper={(swiper) => {
          swiperRef.current = swiper;
        }}
        style={{
          width: "100%",
          paddingBottom: "30px",
        }}
      >
        {entries.map((entry) => (
          <SwiperSlide
            key={entry.id}
            style={{
              display: "flex",
              justifyContent: "center",
            }}
          >
            <DiaryCard
              date={getFormatToday(entry.created_at, "short")}
              content={entry.content}
            />
          </SwiperSlide>
        ))}
      </Swiper>

pagination 스타일

밑의 dots를 꾸미고 싶다면?

.swiper-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Dot 기본 스타일 */
.swiper-pagination-bullet {
  background-color: #d6bfab;
  opacity: 1;
  margin: 0 2px;
}
.swiper-pagination-bullet-active {
  background-color: #ac7544;
  width: 20.8px;
  height: 5.2px;
  border-radius: 26px;
  transition: all 0.3s ease;
}

css 파일 하나 만들고 이렇게 원하는 스타일로 정의해주면 된다!


이 라이브러리는 유용하지만 가끔 .. 내가 원하는대로 커스텀이 안될때도 있다.. 예를 들어 한번에 보여질 페이지를 정하는게 아니라 그냥 간격만 정하고 싶을때! 그럴땐 그냥 직접 구현하는게 속편하긴 하돠

profile
프론트엔드 엔지니어를 희망합니다 :-)

0개의 댓글