A testimonial carousel you can drag, flick and step through

Build a draggable testimonial carousel in React with Motion: card-by-card snapping, flick momentum, a readable scroll rail, arrow keys and upright swipes left to the page.

6 min read

The real component. Click the picture to open it live and try it before you read how it was built.

Carousels are often annoying because they fight the visitor. This one is held, not walled: it follows the drag, carries a flick and settles on the nearest card without a wobble.

Snapping with a flick

On release, the release speed times a short duration gives how far a flick carries. The nearest card stop to that point wins, and a heavy, well-damped spring glides the row there. A little give past either end makes the edges feel soft.

src/registry/testimonials/drag-carousel/use-snap-carousel.ts

"use client";

import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { animate, useMotionValue, useTransform, type MotionValue, type PanInfo, type Transition } from "motion/react";
import { usePrefersReducedMotion } from "@/hooks/use-prefers-reduced-motion";

// A heavy, well-damped spring: the track glides to its stop and settles without a wobble.
const SNAP_SPRING: Transition = { type: "spring", stiffness: 260, damping: 38, mass: 0.9 };
const STILL: Transition = { duration: 0 };
// How far a flick carries: the release speed (px/s) times this many seconds, before the nearest stop is picked.
const MOMENTUM_S = 0.22;

interface TrackMetrics {
  // Distance from one card's left edge to the next one's.
  step: number;
  // How far the track can travel before its last card meets the viewport's right edge.
  maxScroll: number;
  // The share of the track the viewport shows, for the progress thumb's width.
  visibleShare: number;
}

export interface SnapCarousel {
  viewportRef: RefObject<HTMLDivElement | null>;
  trackRef: RefObject<HTMLUListElement | null>;
  x: MotionValue<number>;
  // 0 at the start, 1 when the last card is in view; follows the finger while dragging.
  progress: MotionValue<number>;
  index: number;
  lastIndex: number;
  visibleShare: number;
  maxScroll: number;
  goTo: (index: number) => void;
  handleDragEnd: (event: PointerEvent | MouseEvent | TouchEvent, info: PanInfo) => void;
}

const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);

function measureTrack(viewport: HTMLElement, track: HTMLElement): TrackMetrics {
  const [first, second] = Array.from(track.children) as HTMLElement[];
  const step = first && second ? second.offsetLeft - first.offsetLeft : (first?.offsetWidth ?? 0);
  const maxScroll = Math.max(0, track.scrollWidth - viewport.clientWidth);
  return {
    step,
    maxScroll,
    visibleShare: track.scrollWidth ? Math.min(1, viewport.clientWidth / track.scrollWidth) : 1,
  };
}

// Measures the row after mount and again whenever the viewport or the row changes size.
function useTrackMetrics(
  viewportRef: RefObject<HTMLDivElement | null>,
  trackRef: RefObject<HTMLUListElement | null>,
): TrackMetrics {
  const [metrics, setMetrics] = useState<TrackMetrics>({ step: 0, maxScroll: 0, visibleShare: 1 });
  useEffect(() => {
    const viewport = viewportRef.current;
    const track = trackRef.current;
    if (!viewport || !track) return;
    const update = () => setMetrics(measureTrack(viewport, track));
    update();
    const observer = new ResizeObserver(update);
    observer.observe(viewport);
    observer.observe(track);
    return () => observer.disconnect();
  }, [viewportRef, trackRef]);
  return metrics;
}

// A row of cards that drags sideways and snaps to the nearest card, carrying a flick's momentum. Stops are card
// edges; the last stop is wherever the final card lines up with the right edge, so the row never ends on a gap.
export function useSnapCarousel(): SnapCarousel {
  const viewportRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLUListElement>(null);
  const x = useMotionValue(0);
  const [index, setIndex] = useState(0);
  const isStill = usePrefersReducedMotion();
  const { step, maxScroll, visibleShare } = useTrackMetrics(viewportRef, trackRef);
  const lastIndex = step > 0 ? Math.ceil(maxScroll / step - 0.01) : 0;
  const progress = useTransform(x, (offset) => (maxScroll > 0 ? clamp(-offset / maxScroll, 0, 1) : 0));

  const offsetFor = useCallback((target: number) => -Math.min(target * step, maxScroll), [step, maxScroll]);

  // A resize moves the stops, so the track re-settles on the card it was showing.
  useEffect(() => {
    x.set(offsetFor(Math.min(index, lastIndex)));
    // Only a new measurement should jump the track; index changes animate through goTo.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [offsetFor, lastIndex, x]);

  const goTo = useCallback(
    (target: number) => {
      const next = clamp(target, 0, lastIndex);
      setIndex(next);
      animate(x, offsetFor(next), isStill ? STILL : SNAP_SPRING);
    },
    [lastIndex, offsetFor, isStill, x],
  );

  const handleDragEnd = useCallback(
    (_event: PointerEvent | MouseEvent | TouchEvent, info: PanInfo) => {
      if (step <= 0) return;
      const landing = x.get() + info.velocity.x * MOMENTUM_S;
      goTo(Math.round(-landing / step));
    },
    [goTo, step, x],
  );

  return { viewportRef, trackRef, x, progress, index, lastIndex, visibleShare, maxScroll, goTo, handleDragEnd };
}
The snapping hook

A rail you can read

Below the row, a thin rail's thumb is as wide as the visible part of the row and slides with it, like a scrollbar that tells you where you are. Previous and next buttons grey out at either end.

Keyboard and phones

While focused, the arrow keys, Home and End step through cards. On phones, an upright swipe is handed back to the page so scrolling never gets stuck.

src/registry/testimonials/drag-carousel/testimonial-track.tsx

"use client";

import type { KeyboardEvent } from "react";
import { motion } from "motion/react";
import { cn } from "@/lib/utils";
import { CarouselControls } from "./carousel-controls";
import { TestimonialCard } from "./testimonial-card";
import type { Testimonial } from "./types";
import { useSnapCarousel } from "./use-snap-carousel";

// A little give past either end, so the row feels held rather than walled off.
const EDGE_ELASTIC = 0.12;

interface TestimonialTrackProps {
  testimonials: Testimonial[];
  label: string;
  className?: string;
}

// The draggable row of testimonial cards with its controls. It snaps card by card, carries a flick, answers the
// arrow keys (and Home and End) while focused, and lets the page scroll vertically when a phone swipe is upright.
export function TestimonialTrack({ testimonials, label, className }: TestimonialTrackProps) {
  const { viewportRef, trackRef, x, progress, index, lastIndex, visibleShare, maxScroll, goTo, handleDragEnd } =
    useSnapCarousel();

  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const targets: Record<string, number> = { ArrowLeft: index - 1, ArrowRight: index + 1, Home: 0, End: lastIndex };
    if (!(event.key in targets)) return;
    event.preventDefault();
    goTo(targets[event.key]);
  };

  return (
    <div className={cn("flex flex-col gap-8", className)}>
      {/* Focus shows as an outline rather than a ring: outlines paint above the cards that run past the viewport. */}
      <div
        ref={viewportRef}
        role="region"
        aria-roledescription="carousel"
        aria-label={label}
        tabIndex={0}
        onKeyDown={handleKeyDown}
        className="rounded-3xl outline-none focus-visible:outline-3 focus-visible:outline-offset-4 focus-visible:outline-ring/50"
      >
        <motion.ul
          ref={trackRef}
          drag="x"
          dragConstraints={{ left: -maxScroll, right: 0 }}
          dragElastic={EDGE_ELASTIC}
          dragMomentum={false}
          onDragEnd={handleDragEnd}
          style={{ x }}
          className="flex w-max cursor-grab touch-pan-y gap-4 select-none active:cursor-grabbing sm:gap-5"
        >
          {testimonials.map((testimonial, cardIndex) => (
            <li
              key={testimonial.company}
              role="group"
              aria-roledescription="slide"
              aria-label={`${cardIndex + 1} of ${testimonials.length}`}
              className="w-76 shrink-0 sm:w-96"
            >
              <TestimonialCard testimonial={testimonial} index={cardIndex} />
            </li>
          ))}
        </motion.ul>
      </div>
      <CarouselControls
        progress={progress}
        visibleShare={visibleShare}
        index={index}
        lastIndex={lastIndex}
        onStep={(direction) => goTo(index + direction)}
      />
    </div>
  );
}
The track

More articles