캐러셀 구현을 위해 종종 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>
자주 사용하는 옵션
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]}
...
>
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>
밑의 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 파일 하나 만들고 이렇게 원하는 스타일로 정의해주면 된다!
이 라이브러리는 유용하지만 가끔 .. 내가 원하는대로 커스텀이 안될때도 있다.. 예를 들어 한번에 보여질 페이지를 정하는게 아니라 그냥 간격만 정하고 싶을때! 그럴땐 그냥 직접 구현하는게 속편하긴 하돠