[javascript] swiper, scrollLeft

suyeon kim·2024년 5월 4일

scrollLeft

row 컴포넌트를 arrow 엘리먼트를 클릭했을 때 좌우로 부드럽게 이동시키고 싶을 때 사용가능하다.

예시

const handleMove = (id, direction) => {
  const scrollDiv = document.getElementById(id);
  if (direction == "next") {
    scrollDiv.scrollLeft += window.innerWidth - 80;
  } else {
    scrollDiv.scrollLeft -= window.innerWidth - 80;
  }
};

<div className="arrow next" onClick={() => handleMove(id, "next")}>
  <span className="next">{">"}</span>
</div>;


// css

.row_item_wrapper {
  overflow-x: scroll;
  -ms-overflow-style: none;
  scrollbar-width: none;
  ::-webkit-scrollbar {
    display: none;
  }

-=는 할당 연산자의 일종으로, 현재 변수의 값을 우측 피연산자의 값만큼 감소시킨 후 그 결과를 다시 왼쪽 피연산자에 할당한다. 예를 들어, x -= y는 x = x - y와 동일하다. 즉, 변수 x의 현재 값에서 변수 y의 값을 빼고 그 결과를 다시 x에 할당한다.

따라서 document.getElementById(id).scrollLeft -= window.innerWidth - 80;는 다음과 같은 의미를 가진다.
현재 스크롤 위치에서 (window.innerWidth - 80)만큼을 뺀 값을 현재 스크롤 위치로 다시 할당한다. 이는 스크롤을 왼쪽으로 이동시키는 것을 의미한다.

부드럽게 움직이게 하기 위해서, css에 scroll-behavior: smooth;를 잊지말고 넣어주자.

swiper

사용법

설치
npm i swiper


import

import { Swiper, SwiperSlide } from 'swiper/react';
// import { Navigation, Pagination, Scrollbar } from 'swiper';  -> 옵션임!
import 'swiper/css';

// 옵션임!
// import 'swiper/css/navigation';
// import 'swiper/css/pagination';
// import 'swiper/css/scrollbar';


예시

import React from 'react';
import SwiperCore, { Navigation, Pagination } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/swiper-bundle.css';

// Swiper의 Navigation과 Pagination 모듈을 초기화
//SwiperCore.use([Navigation, Scrollbar, Autoplay, Pagination]);
// 최신 버전에서는 더는 사용하지 않음

const Slider = () => {
  return (
    <Swiper
      modules={[Navigation, Scrollbar, Autoplay]}
      loop={true} // 슬라이드 루프
        spaceBetween={50} // 슬라이스 사이 간격
        slidesPerView={3} // 보여질 슬라이스 수
        navigation={true} // prev, next button
        autoplay={{
          delay: 2500,
          disableOnInteraction: false, // 사용자 상호작용시 슬라이더 일시 정지 비활성
        }}
    >
      <SwiperSlide>
          슬라이드 1
      </SwiperSlide>
      <SwiperSlide>
          슬라이드 2
      </SwiperSlide>
      <SwiperSlide>
          슬라이드 3
      </SwiperSlide>
    </Swiper>
  );
}

export default Slider;

next.js 에서의 사용

'use client'를 상단에 붙혀서 사용해야한다.

0개의 댓글