Embla Carousel 사용법 요약 (Feat. Next.js)

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;
  • 캐러셀 구성요소 코드

나는 이것을 겪었고 문제가 발생했습니다

페이지가 로드될 때 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
  • 자동 재생 패키지 설치

  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));


이거 만드는데 이틀걸렸어요…

매끄럽고 부드럽게 스크롤

캐러셀 라이브러리 중에서는 용량이 작다고 해서 성능적으로는 좋은 것 같습니다.

그리고 모바일에서도 잘 됩니다!