ネイティブのスクロールスナップで作る、React の推薦カルーセル

どのマーケティングサイトにもあるレビューセクション。1 枚のカードが中央、隣のカードが後ろで傾き、下にドット、スワイプかクリックで次へ。スライダーライブラリが売るのはまさにこれです。ブラウザはすでに両方の半分を持っています——着地には 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 の典型的な用途です。3 枚の見えるカード、中央は平ら、ページネーションのドット、自動再生。そのどれもが CSS か、このライブラリの API 上の数行です。

唯一きちんとやるべきこと:ドラッグ

mandatory のスナップコンテナはプログラムからの scrollLeft への書き込みをすべてスナップするため、マウスドラッグのレシピをそのまま使うとカードごとにつっかえます。スクロールスナップの例が解決策を示します。ジェスチャーの間はスナップを切り、離したら scrollToItem で最も近いカードへ滑らかに移動し、その移動が落ち着いてからスナップを CSS に返す——早く戻すと滑らかに動く代わりにジャンプします。タッチにはこれらは不要です。行は本物のスクロールコンテナだからです。

自動再生、ループ、そしてあなたのもの

自動再生は同じ scrollToItem を呼ぶタイマーで、ホバー、フォーカス、視差効果の低減で一時停止します。無限ループも組み合わせられます。テレポートはループ 1 周分、つまり整数個のスナップ位置だけ移動するからです。カードはあなたのコンポーネントです——アバター、評価、引用、ロゴ——そして幾何はカスタムプロパティ 3 つ、カード幅、間隔、傾きだけです。

パターン、最小構成

スナップと傾きはスタイルシート。矢印とドットは 1 回の計測と 1 つの 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 件)