React에서 간단한 Carousel/Slider 만들기
Source: Dev.to
캐러셀 컴포넌트
캐러셀(또는 슬라이더)은 이미지나 콘텐츠 시리즈를 한 번에 하나씩 표시하는 훌륭한 방법입니다. 버튼을 사용해 슬라이드를 이동할 수 있습니다. 아래는 React를 이용한 간단한 구현 예시입니다.
import { useEffect, useState } from 'react';
import { shortList, list, longList } from '../data';
import { FaQuoteRight } from 'react-icons/fa';
import { FiChevronLeft, FiChevronRight } from 'react-icons/fi';
const Carousel = () => {
const [people, setPeople] = useState(longList);
const [currentPersonIndex, setCurrentPersonIndex] = useState(0);
const prevSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex - 1 + people.length) % people.length;
return newIndex;
});
};
const nextSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex + 1) % people.length;
return newIndex;
});
};
useEffect(() => {
const sliderId = setInterval(() => {
nextSlide();
}, 2000);
return () => {
clearInterval(sliderId);
};
}, [currentPersonIndex]);
return (
{people.map((person, personIndex) => {
const { id, name, image, title, quote } = person;
return (
<div key={id}>
<h3>{name}</h3>
<p>{title}</p>
<p>{quote}</p>
</div>
);
})}
);
};
export default Carousel;
함수 설명: nextSlide와 prevSlide
nextSlide 함수
const nextSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex + 1) % people.length;
return newIndex;
});
};
동작 방식
- 현재 인덱스(
currentPersonIndex)를 읽습니다. - 다음 항목으로 이동하기 위해 1을 더합니다.
- 모듈로 연산자(
% people.length)를 사용해 인덱스가 리스트 끝에 도달하면 0으로 되돌려 연속 루프를 만듭니다.
예시
currentPersonIndex가 4(마지막 사람)이고 리스트에 5개의 항목이 있다면, (4 + 1) % 5는 0이 되므로 캐러셀은 첫 번째 사람으로 돌아갑니다.
prevSlide 함수
const prevSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex - 1 + people.length) % people.length;
return newIndex;
});
};
동작 방식
- 현재 인덱스를 읽습니다.
- 이전 항목으로 이동하기 위해 1을 빼습니다.
- 모듈로 연산을 적용하기 전에
people.length를 더해 결과가 양수가 되도록 하여, 첫 번째 항목에서 마지막 항목으로 감싸집니다.
예시
currentPersonIndex가 0(첫 번째 사람)이고 리스트에 5개의 항목이 있다면, (-1 + 5) % 5는 4가 되어 캐러셀이 마지막 사람으로 이동합니다.
기억해야 할 핵심 포인트
- 표현식
% people.length는 캐러셀이 앞뒤로 순환하도록 해줍니다. nextSlide는 인덱스를 증가시키고,prevSlide는 인덱스를 감소시킵니다.currentPersonIndex를 업데이트하면 리렌더링이 트리거되어 해당 슬라이드가 표시됩니다.