네이티브 스크롤 스냅 위의 React 후기 캐러셀

모든 마케팅 사이트에 있는 후기 섹션: 카드 한 장이 가운데, 이웃 카드는 뒤에서 기울고, 아래에는 점, 스와이프나 클릭으로 다음 카드로. 슬라이더 라이브러리가 파는 것이 바로 이것입니다. 브라우저는 이미 두 반쪽을 갖고 있습니다 — 안착에는 scroll-snap-type, 기울기에는 스크롤 기반 애니메이션 — 그리고 이 라이브러리는 그 둘 다 아닌 부분을 더합니다. 어느 카드가 현재인지 아는 것입니다.

Mia ChenProduct designer

“Setup took an afternoon and the first report landed in my inbox the next morning. I have not opened the old spreadsheet since.”

Tomás ReyesEngineering manager

“The weekly digest is the only email my team reads end to end. Short, specific, and it names the person who unblocked you.”

Aisha OkaforFounder

“I wanted numbers I could defend in a board meeting. Every figure links back to the source, so nobody has to take my word for it.”

Jonas LindqvistData analyst

“Exports are plain CSV with sane column names. That alone saved me a script I had been maintaining for two years.”

Priya NatarajanOperations lead

“Support answered a Sunday question in twenty minutes with a fix, not a ticket number. That is what I pay for.”

Lucas MoreauFreelance developer

“The API does exactly what the docs say, and the docs are one page. I shipped the integration before lunch.”

스와이프하거나, 드래그하거나, 화살표와 점을 써 보세요 — 행은 매번 카드 위에서 멈춥니다.

여기서 슬라이더 라이브러리가 실제로 하는 일

후기 캐러셀은 Swiper의 전형적인 용도입니다. 보이는 카드 세 장, 가운데는 평평, 페이지네이션 점, 자동 재생. 이것들 하나하나가 CSS이거나 이 라이브러리 API 위의 몇 줄입니다.

제대로 해야 할 한 가지: 드래그

mandatory 스냅 컨테이너는 프로그램의 모든 scrollLeft 쓰기를 스냅하므로, 마우스 드래그 레시피를 그대로 쓰면 카드마다 덜컥거립니다. 스크롤 스냅 예제가 해법을 보여 줍니다. 제스처 동안 스냅을 끄고, 놓으면 scrollToItem으로 가장 가까운 카드까지 미끄러지며, 그 이동이 안정된 뒤에 스냅을 CSS에 돌려줍니다 — 더 일찍 켜면 미끄러지는 대신 점프합니다. 터치에는 이 중 아무것도 필요 없습니다. 행은 진짜 스크롤 컨테이너이기 때문입니다.

자동 재생, 루프, 그리고 여러분의 몫

자동 재생은 같은 scrollToItem을 호출하는 타이머로, 호버, 포커스, 동작 줄이기에서 멈춥니다. 무한 루프도 조합됩니다. 텔레포트가 루프 한 바퀴 길이, 곧 정수 개의 스냅 지점만큼 이동하기 때문입니다. 카드는 여러분의 컴포넌트이고 — 아바타, 평점, 인용, 로고 — 기하는 커스텀 프로퍼티 세 개, 카드 너비, 간격, 기울기뿐입니다.

패턴, 최소 구성

스냅과 기울기는 스타일시트이고, 화살표와 점은 측정 한 번과 scrollToItem 하나입니다. 위 데모는 여기에 카드를 더한 것입니다.

TestimonialCarousel.tsx
function TestimonialCarousel({ reviews }: { reviews: Review[] }) {
  const [active, setActive] = React.useState(0);

  return (
    <ScrollMenu
      scrollContainerClassName="snap-rail"
      itemClassName="snap-slot"
      onScroll={(api) => setActive(nearestIndex(api, reviews))}
      LeftArrow={<Arrow id={reviews[active - 1]?.id} />}
      RightArrow={<Arrow id={reviews[active + 1]?.id} />}
    >
      {reviews.map((review) => (
        <ReviewCard itemId={review.id} key={review.id} {...review} />
      ))}
    </ScrollMenu>
  );
}

// The card whose center is closest to the rail's center.
function nearestIndex(api: publicApiType, reviews: Review[]) {
  const rail = api.scrollContainer.current!;
  const middle = rail.scrollLeft + rail.clientWidth / 2;
  const distances = reviews.map(({ id }) => {
    const slot = api.getItemElementById(id) as HTMLElement;
    return Math.abs(slot.offsetLeft + slot.offsetWidth / 2 - middle);
  });
  return distances.indexOf(Math.min(...distances));
}

// Arrows step one card: the neighbour of the centered one, centered.
function Arrow({ id }: { id?: string }) {
  const api = React.useContext<publicApiType>(VisibilityContext);
  const step = () => {
    const el = id && api.getItemElementById(id);
    if (el) api.scrollToItem(el, 'smooth', 'center');
  };
  return <button disabled={!id} onClick={step}>→</button>;
}

/* .snap-rail — the browser lands every swipe on a card:
     scroll-snap-type: x mandatory;
     padding-inline: calc(50% - var(--card) / 2);
   .snap-slot — scroll-snap-align: center;
   The fan is the snap.css panel on the homepage. */

또는 shadcn 컴포넌트로 설치하기

snap-carousel 레지스트리 항목은 이 패턴 전체 — 스냅, 부채꼴, 화살표, 점, 가장 가까운 카드에 안착하는 드래그 — 를 Tailwind로 스타일된 컴포넌트로 components/ui/에 넣어 줍니다. 카드는 직접 가져오세요:

shadcn
npx shadcn@latest add https://react-horizontal-scrolling-menu.dev/r/snap-carousel.json

관련 예제

예제 전체 23개