React/NextJS

Embla Carousel 사용법 정리 (Feat. Next.js)

kohi ☕ 2023. 4. 14. 03:17
yarn add embla-carousel-react
  • embla-carousel-react 패키지 설치

 

import { useEffect, useRef, useState } from 'react';
import { useEmblaCarousel } from 'embla-carousel-react';

function Carousel() {
  const [viewportRef, embla] = useEmblaCarousel({ loop: true });
  const [cardInfo, setCardInfo] = useState<FeedListType[]>([]);

  useEffect(() => {
 	// 카드인포데이터패칭
  }, []);

  return (
    <div className="overflow-hidden" ref={viewportRef}>
      <div className="flex">
        {cardInfo.map((card) => {
          return (
            <div key={card.docId} style={{ display: 'flex', position: 'relative' }}>
              <FeedCard card={card} />
            </div>
          );
        })}
      </div>
  );
}

export default Carousel;
  • Carousel 컴포넌트 코드


여기까지 했다가 만난 문제 상황

페이지가 로드될 때 Embla Carousel이 작동하지 않고 창을 리사이징하면 작동하는 경우

  • Embla Carousel의 초기화 시점이 올바르지 않기 때문
  • Next.js는 페이지의 초기 렌더링 시 서버와 클라이언트에서 모두 실행되기 때문에, 이를 고려하여 Embla Carousel을 초기화해야 한다.
  • useEffect 훅과 조건문을 사용하여 Embla Carousel을 클라이언트 측에서 초기화하도록 만들어야 한다.
  • Embla Carousel이 초기화될 때 데이터가 로드되지 않아서도 발생할 수 있음

 

수정한 코드

  const [cardInfo, setCardInfo] = useState<FeedListType[]>([]);
  const [viewportRef, embla] = useEmblaCarousel(
    {
      loop: true,
    }
  );

  useEffect(() => {
    if (embla && cardInfo.length > 0) {
      embla.reInit();
    }
  }, [embla, cardInfo]);
  • 페이지가 로드됐고 카드인포가 있을 때 Embla Carousel을 초기화한다.

 

여기에 오토 기능 추가

yarn add embla-carousel-autoplay
  • autoplay 패키지 설치

 

  const [cardInfo, setCardInfo] = useState<FeedListType[]>([]);
  const autoplayOptions = {
    delay: 3000,
  };
  const [viewportRef, embla] = useEmblaCarousel(
    {
      loop: true,
    },
    [Autoplay(autoplayOptions)],
  );

  useEffect(() => {
    if (embla && cardInfo.length > 0) {
      embla.reInit();
    }
  }, [embla, cardInfo]);

 

이거 만드는데 뻥 안 치고 이틀 걸렸다...

스크롤링 유연하게 술술 잘 넘어간다

캐러셀 라이브러리 중에 용량 작은 편이라는데 그래서 그런지 성능 측면에서도 좋은 거 같음

그리고 이거 모바일에서도 잘 됨!!!