Type something to search...

12 Swiper 캐러셀 적용과 프로젝트 마무리

1. Swiper란?

Swiper(스와이퍼)는 터치 슬라이드/캐러셀(Carousel, 회전목마형 슬라이드)을 쉽게 만들어주는 라이브러리이다. 넷플릭스, 유튜브, 쿠팡 같은 서비스에서 콘텐츠를 좌우로 넘기는 UI가 바로 이것이다.

이번 편에서는 6편에서 만든 Section.jsx의 그리드 레이아웃을 Swiper 캐러셀로 업그레이드한다.

순서만들 기능핵심 개념
1단계Swiper 기본 적용Swiper, SwiperSlide, 모듈 import
2단계반응형 설정breakpoints
3단계자동 재생Autoplay 모듈

2. Swiper 설치 확인

1편에서 이미 설치했지만, 혹시 빠뜨렸다면 아래 명령어를 실행한다.

Terminal window
1
npm install swiper

3. 1단계 — Swiper 기본 적용

src/components/Section.jsx 파일을 열고 전체를 아래로 교체한다.

먼저 import 부분부터 작성한다.

src/components/Section.jsx
1
import Card from "./Card";
2
import { Swiper, SwiperSlide } from 'swiper/react';
3
import { Navigation, Pagination } from 'swiper/modules';
4
import 'swiper/css';
5
import 'swiper/css/navigation';
6
import 'swiper/css/pagination';
설명
2Swiper(컨테이너)와 SwiperSlide(각 슬라이드)를 가져온다.
3Navigation(좌우 화살표)과 Pagination(하단 점) 모듈을 가져온다. Swiper는 필요한 기능만 모듈로 불러오는 방식을 쓴다.
4-6Swiper CSS와 각 모듈 전용 CSS를 불러온다. 이것이 없으면 레이아웃이 깨진다.

이어서 컴포넌트 본체를 작성한다.

src/components/Section.jsx
1
export default function Section({ title, items }) {
2
return (
3
<section className="bg-black py-10 px-4">
4
<div className="container mx-auto">
5
<h2 className="text-[32px] font-bold mb-6">{title}</h2>
6
<Swiper
7
modules={[Navigation, Pagination]}
8
spaceBetween={16}
9
slidesPerView={1}
10
navigation
11
pagination={{ clickable: true }}
12
>
13
{items.map((m) => (
14
<SwiperSlide key={m.id}>
15
<Card movie={m} />
16
</SwiperSlide>
17
))}
18
</Swiper>
19
</div>
20
</section>
21
);
22
}
설명
7modules에 사용할 모듈을 배열로 전달한다.
8spaceBetween={16}은 슬라이드 간 간격을 16px로 설정한다.
9slidesPerView={1}은 한 번에 1개의 슬라이드를 보여준다.
10navigation은 좌우 화살표 버튼을 활성화한다.
11pagination={{ clickable: true }}는 하단에 클릭 가능한 점 인디케이터를 표시한다.
13-16영화 배열을 순회하며 각 영화를 SwiperSlide로 감싸고, 그 안에 Card를 넣는다.

여기까지 저장하면 슬라이드가 1개씩 보이는 기본 캐러셀이 완성된다.


4. 2단계 — 반응형 설정

모바일에서는 1개, 태블릿에서는 3개, 데스크톱에서는 4개의 카드가 보이게 breakpoints를 추가한다. Swiper 태그 안에 속성을 추가한다.

src/components/Section.jsx
1
<Swiper
2
modules={[Navigation, Pagination]}
3
spaceBetween={16}
4
slidesPerView={1}
5
navigation
6
pagination={{ clickable: true }}
7
breakpoints={{
8
640: { slidesPerView: 2 },
9
768: { slidesPerView: 3 },
10
1024: { slidesPerView: 4 },
11
}}
12
>

breakpoints는 화면 너비에 따라 보이는 슬라이드 수를 조절한다.

화면 너비보이는 카드 수해당 기기
0 ~ 639px1개스마트폰
640 ~ 767px2개큰 스마트폰 / 작은 태블릿
768 ~ 1023px3개태블릿
1024px 이상4개노트북 / 데스크톱

요약

숫자는 프로젝트에 맞게 자유롭게 조절할 수 있다. slidesPerView: 5로 바꾸면 한 번에 5개 카드가 보인다.


5. 3단계 — 자동 재생 추가

슬라이드가 자동으로 넘어가게 하려면 Autoplay 모듈을 추가한다.

import에 Autoplay를 추가한다.

src/components/Section.jsx
1
import { Navigation, Pagination, Autoplay } from 'swiper/modules';

그리고 Swiper 태그에 Autoplay 모듈과 옵션을 추가한다.

src/components/Section.jsx
1
<Swiper
2
modules={[Navigation, Pagination, Autoplay]}
3
spaceBetween={16}
4
slidesPerView={1}
5
navigation
6
pagination={{ clickable: true }}
7
autoplay={{ delay: 3000, disableOnInteraction: false }}
8
loop={true}
9
breakpoints={{
10
640: { slidesPerView: 2 },
11
768: { slidesPerView: 3 },
12
1024: { slidesPerView: 4 },
13
}}
14
>
옵션설명
delay: 30003초(3000ms)마다 다음 슬라이드로 넘긴다.
disableOnInteraction: false사용자가 수동으로 넘긴 뒤에도 자동 재생을 계속한다.
loop={true}마지막 슬라이드 다음에 처음으로 무한 반복한다.

6. 자주 쓰는 Swiper 옵션 모음

옵션값 예시설명
slidesPerView4한 번에 보이는 슬라이드 수
spaceBetween16슬라이드 간 간격 (px)
navigationtrue좌우 화살표 표시
pagination{ clickable: true }하단 점 인디케이터 표시
looptrue무한 반복
grabCursortrue마우스 커서가 잡기(grab) 모양으로 바뀐다
옵션값 예시설명
delay3000자동 넘김 간격 (ms)
disableOnInteractionfalse수동 조작 후에도 자동 재생 유지
pauseOnMouseEntertrue마우스를 올리면 일시정지
reverseDirectiontrue역방향으로 자동 넘김

Swiper 기본 화살표 대신 직접 디자인한 화살표를 사용할 수도 있다.

src/components/Section.jsx
1
import { useRef } from "react";
2
3
export default function Section({ title, items }) {
4
const prevRef = useRef(null);
5
const nextRef = useRef(null);
6
7
return (
8
<section className="bg-black py-10 px-4">
9
<div className="container mx-auto relative">
10
<h2 className="text-[32px] font-bold mb-6">{title}</h2>
11
<button ref={prevRef} className="absolute left-0 top-1/2 z-10 text-white text-2xl">◀</button>
12
<button ref={nextRef} className="absolute right-0 top-1/2 z-10 text-white text-2xl">▶</button>
13
<Swiper
14
modules={[Navigation]}
15
navigation={{ prevEl: prevRef.current, nextEl: nextRef.current }}
16
onBeforeInit={(swiper) => {
17
swiper.params.navigation.prevEl = prevRef.current;
18
swiper.params.navigation.nextEl = nextRef.current;
19
}}
20
slidesPerView={4}
21
spaceBetween={16}
22
>
23
{items.map((m) => (
24
<SwiperSlide key={m.id}>
25
<Card movie={m} />
26
</SwiperSlide>
27
))}
28
</Swiper>
29
</div>
30
</section>
31
);
32
}

useRef(유즈레프)로 버튼의 DOM 참조를 만들고, navigationprevEl/nextEl에 연결한다. onBeforeInit은 Swiper 초기화 직전에 참조를 다시 설정하는 안전장치이다.


7. 자주 발생하는 에러

Swiper가 설치되지 않았을 가능성이 높다. npm install swiper를 실행한 뒤 개발 서버를 재시작한다.

import 'swiper/css/navigation';을 빠뜨리지 않았는지 확인한다. modules={[Navigation]}에 Navigation이 포함되어 있어야 한다.

.env 파일의 API 키를 확인한다. 수정 후 반드시 개발 서버를 재시작한다.

무료 호스팅(Render)은 사용하지 않으면 슬립(Sleep) 상태가 된다. 첫 요청 시 30초~1분 기다리면 서버가 깨어난다.


8. 빌드와 배포

개발이 완료되면 프로덕션(Production, 운영) 빌드를 생성한다.

Terminal window
1
npm run build
설명
1Vite가 코드를 최적화하고 dist 폴더에 배포용 파일을 생성한다. Vercel(버셀), Netlify(넷틀리파이) 같은 호스팅 서비스에 업로드하면 된다.

빌드 결과물을 로컬에서 미리 확인하려면 아래 명령어를 실행한다.

Terminal window
1
npm run preview

9. 전체 프로젝트 파일 최종 점검


10. 시리즈 전체 요약

핵심 내용
1편프로젝트 생성, 패키지 설치, 환경 설정
2편React 진입점, React Router 라우팅
3편Axios 인스턴스, API 키 환경 변수
4편App.jsx 레이아웃, useEffect 데이터 로딩
5편Home 메인 페이지, 히어로 영상, useOutletContext
6편Section/Card 컴포넌트, map(), Props 전달
7편MovieDetail 상세 페이지, useParams, 조건부 렌더링
8편플로팅 챗봇 버튼, 모달, 이벤트 버블링
9편Chatbot 채팅 기능, fetch POST, 스프레드 연산자
10편Swiper 캐러셀, 반응형 슬라이드, 프로젝트 마무리

이 시리즈를 완료하면 React의 핵심 개념(컴포넌트, Props, State, Hook, 라우팅)과 실전 API 연동, 외부 라이브러리 활용까지 경험한 것이다. 이제 이 GOFLIX 프로젝트를 기반으로 기능을 추가하거나, 자신만의 프로젝트를 시작해 보자.