Một carousel lời chứng thực trong React, trên scroll snap gốc

Mục đánh giá trên mọi trang marketing: một thẻ ở giữa, các thẻ kề nghiêng phía sau, chấm bên dưới, vuốt hoặc bấm để sang thẻ tiếp. Thư viện slider bán đúng thứ này. Trình duyệt đã có cả hai nửa — scroll-snap-type để dừng đúng chỗ và hoạt ảnh theo cuộn để nghiêng — còn thư viện này thêm phần không thuộc về cả hai: biết thẻ nào đang là hiện tại.

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.”

Vuốt, kéo, hoặc dùng mũi tên và chấm — hàng lần nào cũng dừng trên một thẻ.

Thư viện slider thực sự làm gì ở đây

Carousel lời chứng thực là cách dùng Swiper kinh điển: ba thẻ hiển thị, thẻ giữa phẳng, chấm phân trang, tự phát. Mỗi thứ trong đó hoặc là CSS, hoặc là vài dòng trên API của thư viện này:

Điều duy nhất phải làm đúng: kéo

Một vùng chứa bắt dính bắt buộc sẽ bắt dính mọi lần ghi scrollLeft bằng chương trình, nên công thức kéo bằng chuột dùng nguyên sẽ giật từng thẻ. Ví dụ scroll snap cho thấy cách sửa: tắt bắt dính trong suốt cử chỉ, trượt tới thẻ gần nhất bằng scrollToItem khi thả, và trả bắt dính lại cho CSS khi cú trượt đã ổn định — bật lại sớm hơn sẽ nhảy thay vì trượt. Cảm ứng không cần gì trong số này; hàng là một vùng chứa cuộn thật.

Tự phát, vòng lặp, và phần thuộc về bạn

Tự phát là một bộ đếm giờ gọi cùng scrollToItem, tạm dừng khi rê chuột, khi có focus và khi giảm chuyển động. Vòng lặp vô hạn cũng kết hợp được: lần teleport dịch đúng một độ dài vòng lặp, tức một số nguyên điểm bắt dính. Thẻ là component của bạn — ảnh đại diện, đánh giá, trích dẫn, logo — và hình học chỉ là ba thuộc tính tùy chỉnh: bề rộng thẻ, khoảng cách và độ nghiêng.

Mẫu hình, tối giản

Bắt dính và độ nghiêng nằm trong stylesheet; mũi tên và chấm là một phép đo và một scrollToItem. Demo ở trên là thế này cộng thêm các thẻ.

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. */

Hoặc cài đặt nó như một component shadcn

Mục registry snap-carousel mang cả mẫu — bắt dính, hình quạt, mũi tên, chấm và thao tác kéo đáp xuống thẻ gần nhất — thành một component kiểu Tailwind trong components/ui/ của bạn. Hãy mang thẻ của riêng bạn:

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

Các ví dụ liên quan

Tất cả 23 ví dụ