본문 바로가기
Developing Diary/HanInBridge React Update

[React 오답노트] 리액트에서 Swiperjs 사용하기

by kurooru 2023. 1. 20.

< 목표 >
Swiperjs를 사용하여, 일정 간격으로 자동으로 넘어가는 이미지 슬라이드 만들기
* 먼저 파일 내에 swiperjs를 설치해 주어야 한다.
npm i swiper

swiperjs.jsx -> 슬라이드를 구현해줄 코드
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/css";
import "swiper/css/pagination";
import "./slideStyle.css";

// import required modules
import { Autoplay, Pagination } from "swiper";

export default function SlideShow() {
  return (
    <>
      <Swiper
      	// 수직 슬라이드
        direction={"vertical"}
        // 자동플레이
        autoplay={{
          // 반복 시간
          delay: 3000,
          // 건드렸을 때 다시 재생시키는지 여부
          disableOnInteraction: false
        }}
        pagination={{
          // 클릭했을 때 해당 페이지로 넘어가게 하는 기능
          clickable: true,
        }}
        // 모듈 가져오기
        modules={[Autoplay, Pagination]}
        className="mySwiper"
      >
      // 직접 클래스 삽입
        <SwiperSlide className="img1"></SwiperSlide>
        <SwiperSlide className="img2"></SwiperSlide>
      </Swiper>
    </>
  );
}
slideStyle.css -> 슬라이드 내 요소를 꾸며줄 css 코드
.swiper {
    width: 100%;
    height: 100%;
}

.swiper-wrapper .img1 {
    background-image: url("../../resources/images/consulting/Consulting_1.jpeg");
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

.swiper-wrapper .img2 {
    background-image: url("../../resources/images/consulting/Consulting_2.jpeg");
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

/* important 없으면 안먹음! */
.swiper-pagination-bullet {
    width:25px !important;
    height:25px !important;
}

.swiper-pagination-bullet-active {
	/* swiper-pagination-bullet-active의 색은 color가 아니고 background-color로 지정해야 함! */
    background-color: #A67951 !important;
    width:25px !important;
    height:25px !important;
}
문제의 발생

1. 사진을 넣고 싶었는데 어떻게 해야 들어가는지 도저히 알지 못하였다.

2. 클래스명을 찾을 수 없어 css작업이 힘들었다.

해결 방안

1. 적절한 해결방안인지는 모르겠지만 직접 태그 내에 클래스를 집어넣어 이를 해결하였다.

2. 작업자모드의 element를 보며 하나씩 찾아내었다.

해결 코드
// 직접 클래스 삽입
<SwiperSlide className="img1"></SwiperSlide>
<SwiperSlide className="img2"></SwiperSlide>

이렇게 하나씩 찾는게 가장 빠른듯

그리고 구글링보다 먼저 시도해야할 것은

공식홈페이지 참조라는것을 알게 되었다.