230920 개발일지 TIL - React에서 Swiper를 이용한 이미지 슬라이드 구현

The Web On Everything·2023년 9월 20일
0

개발일지

목록 보기
132/269

React에서 Swiper를 이용한 이미지 슬라이드 구현

1. Swiper 모듈 설치

npm install swiper

2. Swiper 컴포넌트 생성

import React from 'react';
import { Link } from 'react-router-dom';
import {
  Navigation,
  Pagination,
  Scrollbar,
  A11y,
  Autoplay,
} from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

const MainBanner = () => {
    return (
        <div style={{ padding: '0 20px' }}>
            <Swiper
                modules={[Navigation, Pagination, Scrollbar, A11y, Autoplay]}
                pagination={{ clickable: true }}
                autoplay={{
                    delay: 3000,
                    disableOnInteraction: false,
                }}
                style={{ margin: '20px auto 0', width: '100%' }}
            >
              <SwiperSlide>
                  <Link to="#">
                      <img src={PromoBanner1} alt="Promo Banner 1" style={{ width: '100%' }} />
                  </Link>
              </SwiperSlide>
              <SwiperSlide>
                  <Link to="#">
                      <img src={PromoBanner2} alt="Promo Banner 2" style={{ width: '100%' }} />
                  </Link>
              </SwiperSlide>
            </Swiper>
        </div>
    );
};

export default MainBanner;

MainBanner라는 이름의 컴포넌트를 생성한다. 이 컴포넌트는 두 개의 이미지 슬라이드(PromoBanner1과 PromoBanner2)를 포함하고 있다.

위 코드에서는 autoplay 속성을 사용하여 자동 재생 기능을 활성화하였고 delay 옵션으로 각 슬라이드 사이의 지연 시간을 설정해주었다.

3. 순서대로 반복되는 이미지 슬라이드 만들기
첫 번째 이미지와 두 번째 이미지가 순서대로 반복되도록 하려면 Swiper의 loop 속성을 추가하여 무한 반복을 활성화할 수 있다.

<Swiper
  modules={[Navigation, Pagination, Scrollbar, A11y, Autoplay]}
  pagination={{ clickable: true }}
  autoplay={{
    delay: 3000,
    disableOnInteraction: false,
  }}
  loop={true} // 무한 반복 활성화
  style={{ margin: '20px auto 0', width: '100%' }}
>

이렇게 하면 슬라이드가 마지막 이미지 이후에 다시 첫 번째 이미지로 돌아가 순서대로 이미지를 계속해서 보여주게 된다.

profile
오늘은 무슨 오류를 만날까?! 널 만나러 가는 길~ LOL

0개의 댓글