라이브러리

[Swiper] 리액트 스와이퍼 자동 재생 특정 횟수에서 멈추기

순코딩 2025. 1. 14. 16:01

 

 

"use client";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import { Autoplay } from "swiper/modules";
import { useRef, useState } from "react";
import { Swiper as SwiperType } from "swiper/types";

const Product = () => {
  const swiperRef = useRef<SwiperType | null>(null); // 스와이퍼 참조 ref
  const [, setSlideChangeCount] = useState(0); // 슬라이드 자동 재생 횟수
  const MAX_AUTOPLAY_COUNT = 2; // 최대 자동 재생 횟수

  // 자동 재생될 때마다 실행할 함수
  const onAutoPlay = () => {
    setSlideChangeCount((prevCount) => {
      const newCount = prevCount + 1; // 다음 카운트

      // 다음 카운트가 원하는 횟수를 초과하면 자동 재생 중단
      if (newCount >= MAX_AUTOPLAY_COUNT) {
        swiperRef.current?.autoplay.stop(); // 자동 재생 중단
        console.log("자동 재생이 중단되었습니다.");
      }

      return newCount; // 다음 카운트 반영
    });
  };

  return (
    <>
          <Swiper
            onSwiper={(swiper) => {
              // 참조 객체 생성
              swiperRef.current = swiper;

			  // 자동 스와이프 시 실행
              swiper.on("autoplay", () => {
                console.log("Autoplay 진행 중"); 
                onAutoPlay();
              });
            }}
            spaceBetween={0} // 슬라이드 간격
            slidesPerView={1} // 한 번에 보여줄 슬라이드 수
            modules={[Autoplay]}
            autoplay={{
              delay: 1500,
            }}
            loop={true}
          >
    </>
  );
};

export default Product;