React

[React] React에서 swiper 사용하기

코드비버 2025. 1. 21. 14:14

Swiper.js는 웹에서 정말 많이 사용되는 JS 라이브러리이다.

bxSlider나 Slick 등도 있지만 이전에 사용해본 결과 개인적으로 Swiper만큼 안정적으로 느껴지지는 않아서 딱히 선호하진 않는다.

아무튼 리액트로 홈페이지를 만드는 중인데, Swiper를 어떻게 삽입할까 고민하다가 알아본 결과 리액트에선 간단한 명령어로 설치가 가능하다고 해서 바로 시도해봤다.

 

https://swiperjs.com/react

 

Swiper - The Most Modern Mobile Touch Slider

Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.

swiperjs.com

 

내가 구현하고싶은 슬라이더는 pagination이나 scrillbar 없이 navigation만 있으면 되는 간단한 모양이다.

 

npm i swiper

 

터미널을 열고 위의 명령어를 입력하면 리액트에서 Swiper를 사용하기 위해 필요한 패키지를 설치한다.

 

import { useRef } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';

export default () => {
    const prevRef = useRef(null);
    const nextRef = useRef(null);
	
    return (
        <Swiper
            modules={[Navigation]}
            spaceBetween={32}
            slidesPerView={4}
            navigation={{ prevEl: prevRef.current, nextEl: nextRef.current }}
        >
            <SwiperSlide>{/*첫번째 슬라이드*/}</SwiperSlide>
            <SwiperSlide>{/*두번째 슬라이드*/}</SwiperSlide>
            <SwiperSlide>{/*세번째 슬라이드*/}</SwiperSlide>
        </Swiper>
        <div className='navigation_btn'>
            <button type="button" ref={prevRef} className='prev'></button>
            <button type="button" ref={nextRef} className='next'></button>
        </div>
    );
}

 

그 다음 위의 코드처럼  Swiper 작동에 필요한 파일들을 import하고 Swiper 컴포넌트에 속성을 지정하고 아래에 SwiperSlide 컴포넌트를 배치시키는 구조로 사용하면 된다.

 

네비게이션 버튼을 추가로 작성한 이유는 기본 제공되는 네비게이션 버튼을 사용하기 어려웠기 때문이다. 

디자인 시안에는 스와이퍼 컨테이너 바깥에 네비게이션 버튼이 위치하는데, 컨테이너 자체에 overflow:visible 속성을 줘버리면 가려진 슬라이드들까지 모두 보여지기 때문에 CSS 수정만으론 구현이 어려웠다. (혹시 방법 있으면 알려주세요...)

 

먼저 네비게이션 버튼은 여러번 렌더링될 필요가 없으므로 useRef hook을 사용해 최초로 마운트할 prevRef, nextRef를 선언한 다음 네비게이션 버튼으로 사용할 html 코드를 작성하고 각각의 버튼에 ref 속성으로 prevRef, nextRef 속성을 부여한다.

그 다음 Swiper 컴포넌트의 navigation 속성의 prevEl, nextEl 속성을 각 버튼의 ref속성.current로 지정해주면 된다.