Skip to content
Thrum

Carousel

Slides in a row that a reader swipes, scrolls or steps through with buttons: onboarding cards, product shots, quotes. It is CSS scroll snap, so touch and trackpads work natively. When every item matters, a grid or a list shows them all at once and is easier to scan.

Install

npx shadcn@latest add https://thrumui.dev/r/carousel.json

Adds components/ui/carousel.tsx and installs motion. Nothing else in your project changes.

import { Carousel } from "@/components/ui/carousel";

Automatically installs icons chevron-down, chevron-left, chevron-right and chevron-up from the icon set.

Props

PropTypeDefaultDescription
Carousel: orientation"horizontal" | "vertical"Default "horizontal"horizontal slides left and right. vertical slides up and down and needs a height, on CarouselContent or on the carousel.
Carousel: loopbooleanDefault falsePrevious on the first slide goes to the last, and next on the last goes to the first. Without it those buttons are disabled.
Carousel: autoplaynumber–Move to the next slide every this many milliseconds, back to the first after the last. It waits while the pointer is over the carousel, while focus is inside it, and under reduced motion.
Carousel: pausedbooleanDefault falseStop autoplay on the current slide.
Carousel: onIndexChange(index: number) => void–Called with the index of the first slide at least 60% in view, whenever it changes.
Carousel: soundbooleanDefault truePlay a tick when a button, a dot or an arrow key changes the slide, if the visitor has sound on. Swiping and autoplay are silent.
Carousel: aria-labelstring–The carousel's name, such as "Getting started". It is a region, so it needs one.
CarouselContentdiv props–The strip of slides. It scrolls natively, snaps to each slide's start, hides its scrollbar and keeps 12 pixels between slides. Put it directly inside Carousel.
CarouselItemdiv props–One slide, as wide as the carousel. basis-[calc(50%-6px)] in className shows two at once, less half the 12 pixel gap; basis-[calc(33.333%-8px)] shows three.
CarouselPrevious, CarouselNextbutton props–Round 32 pixel buttons over the start and end edges (top and bottom when vertical). Move them with className; aria-label defaults to Previous slide and Next slide.
CarouselDotsdiv props–One 24 pixel button per slide. The current one is a longer, darker bar. Nothing is drawn for a single slide.
classNamestring–On every part: extra classes, merged last.

Motion and sound

Motion

  • Buttons, dots and arrow keys glide the strip to the slide with the browser's smooth scrolling. Swipes and the scroll wheel snap with the browser's own motion.
  • The current dot grows from 6 to 16 pixels over 150 ms.
  • Autoplay changes slide on a timer only while the carousel is not hovered or focused, and is off under reduced motion.
  • Reduced motion: the strip jumps to the slide, the dots change at once, and autoplay does not run.

Sound

  • A tick when a previous or next button, a dot or an arrow key changes the slide. Swiping, scrolling and autoplay are silent.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • It follows the WAI-ARIA carousel pattern: a region with the role description carousel and a name, and slides that are groups with the role description slide and a name such as 2 of 5.
  • The slide strip is a polite live region while the carousel moves only on request, so a new slide is announced; while autoplay runs it is silent.
  • Autoplay stops while the pointer is over the carousel and while focus is inside it, so it never moves under a reader. It never runs under reduced motion.
  • The current dot differs in length as well as colour, and carries aria-current. Every button is at least 24 pixels square.
KeysAction
TabMove between the slide strip, the controls inside slides, the previous and next buttons and the dots.
← / →With focus anywhere in a horizontal carousel: go to the previous or next slide. In right-to-left text they follow the direction of reading.
↑ / ↓With focus anywhere in a vertical carousel: go to the previous or next slide.
Enter / SpacePress the focused button or dot.

Source

components/ui/carousel.tsx
"use client";

import { Children, createContext, isValidElement, useContext, useEffect, useRef, useState, type ComponentProps, type KeyboardEvent, type ReactNode, type RefObject } from "react";

import { cn } from "@/lib/utils";
import { useReducedMotion } from "@/lib/thrum-motion";
import { play } from "@/lib/thrum-sound";
import { ChevronDownIcon } from "@/components/icons/chevron-down";
import { ChevronLeftIcon } from "@/components/icons/chevron-left";
import { ChevronRightIcon } from "@/components/icons/chevron-right";
import { ChevronUpIcon } from "@/components/icons/chevron-up";
import { buttonClass } from "@/components/ui/button";

export type CarouselOrientation = "horizontal" | "vertical";

export type CarouselProps = ComponentProps<"div"> & {
  /** `horizontal` slides left and right; `vertical` up and down, and needs a height. */
  orientation?: CarouselOrientation;
  /** Previous and next wrap around at the ends instead of stopping. */
  loop?: boolean;
  /** Move to the next slide every this many milliseconds. It waits while the pointer is over the carousel, while it holds the focus, and under reduced motion. */
  autoplay?: number;
  /** Stop autoplay where it is. */
  paused?: boolean;
  /** Called with the index of the first slide in view when it changes. */
  onIndexChange?: (index: number) => void;
  /** Play a tick when a button, a dot or an arrow key changes the slide, if the visitor has sound on. */
  sound?: boolean;
};

type Carousel = {
  orientation: CarouselOrientation;
  count: number;
  current: number;
  atStart: boolean;
  atEnd: boolean;
  loop: boolean;
  rotating: boolean;
  go: (index: number) => void;
  step: (by: 1 | -1) => void;
  measure: () => void;
};

const CarouselContext = createContext<Carousel | null>(null);
const SlideIndex = createContext(0);
/** The slide strip's element, apart from the rest so the state above stays plain data. */
const ScrollerContext = createContext<RefObject<HTMLDivElement | null> | null>(null);

const useCarousel = () => {
  const carousel = useContext(CarouselContext);
  if (!carousel) throw new Error("Carousel parts go inside a Carousel.");
  return carousel;
};

/** Scrolls slide `index` to the start of the scroller. The scroller's CSS decides whether it glides. */
function scrollToSlide(scroller: HTMLElement | null, index: number, vertical: boolean) {
  const slide = scroller?.children[index];
  if (!scroller || !(slide instanceof HTMLElement)) return;
  const from = scroller.getBoundingClientRect();
  const to = slide.getBoundingClientRect();
  if (vertical) scroller.scrollBy({ top: to.top - from.top });
  else if (getComputedStyle(scroller).direction === "rtl") scroller.scrollBy({ left: to.right - from.right });
  else scroller.scrollBy({ left: to.left - from.left });
}

/** Whether the scroller is at its start and at its end. */
function edgesOf(el: HTMLElement, vertical: boolean) {
  const position = Math.abs(vertical ? el.scrollTop : el.scrollLeft);
  const room = vertical ? el.scrollHeight - el.clientHeight : el.scrollWidth - el.clientWidth;
  return { atStart: position <= 1, atEnd: position >= room - 1 };
}

type Edges = ReturnType<typeof edgesOf>;
const sameEdges = (a: Edges, b: Edges) => a.atStart === b.atStart && a.atEnd === b.atEnd;

/** The number of slides: the children of the `CarouselContent` placed directly inside the carousel. */
function countSlides(children: ReactNode): number {
  for (const child of Children.toArray(children)) {
    if (isValidElement<{ children?: ReactNode }>(child) && child.type === CarouselContent) return Children.toArray(child.props.children).length;
  }
  return 0;
}

/**
 * Slides in a row that a reader swipes, scrolls or steps through with buttons: product shots, onboarding cards, quotes.
 * It is CSS scroll snap, so touch, trackpads and the scroll wheel work natively. Name it with `aria-label`.
 * Put `CarouselContent` directly inside, with one `CarouselItem` per slide.
 */
export function Carousel({ orientation = "horizontal", loop = false, autoplay, paused = false, onIndexChange, sound = true, className, children, onKeyDown, onPointerEnter, onPointerLeave, onFocus, onBlur, ...props }: CarouselProps) {
  const scroller = useRef<HTMLDivElement>(null);
  const count = countSlides(children);
  const vertical = orientation === "vertical";
  const reduced = useReducedMotion();
  const [current, setCurrent] = useState(0);
  const [edges, setEdges] = useState({ atStart: true, atEnd: count <= 1 });
  const [hovered, setHovered] = useState(false);
  const [focused, setFocused] = useState(false);
  const { atEnd } = edges;
  const rotating = Boolean(autoplay && autoplay > 0 && count > 1 && !paused && !reduced);
  const running = rotating && !hovered && !focused;

  const measure = () => {
    const el = scroller.current;
    if (!el) return;
    const next = edgesOf(el, vertical);
    setEdges((now) => (sameEdges(now, next) ? now : next));
  };

  // The first slide that is at least 60% in view is the current one.
  useEffect(() => {
    const el = scroller.current;
    if (!el || count === 0) return;
    const ratios = new Map<Element, number>();
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) ratios.set(entry.target, entry.intersectionRatio);
        const slides = Array.from(el.children);
        const index = slides.findIndex((slide) => (ratios.get(slide) ?? 0) >= 0.6);
        if (index >= 0) setCurrent(index);
        // Also the first measurement of the edges: two half-width slides already fill the view.
        const next = edgesOf(el, vertical);
        setEdges((now) => (sameEdges(now, next) ? now : next));
      },
      { root: el, threshold: [0, 0.6, 1] },
    );
    for (const slide of Array.from(el.children)) observer.observe(slide);
    return () => observer.disconnect();
  }, [count, vertical]);

  const reported = useRef(0);
  useEffect(() => {
    if (reported.current === current) return;
    reported.current = current;
    onIndexChange?.(current);
  }, [current, onIndexChange]);

  // Autoplay: one timer per slide, so a slide reached by hand gets its full time too.
  useEffect(() => {
    if (!running || !autoplay) return;
    // At the end of the strip, with several slides in view, the next one is the first again.
    const next = atEnd || current + 1 >= count ? 0 : current + 1;
    const timer = setTimeout(() => scrollToSlide(scroller.current, next, vertical), autoplay);
    return () => clearTimeout(timer);
  }, [running, autoplay, current, count, vertical, atEnd]);

  const go = (index: number) => {
    const target = Math.max(0, Math.min(count - 1, index));
    if (target === current) return;
    if (sound) play("tick");
    scrollToSlide(scroller.current, target, vertical);
  };
  const step = (by: 1 | -1) => {
    if (by === 1 && edges.atEnd) return loop ? go(0) : undefined;
    if (by === -1 && edges.atStart) return loop ? go(count - 1) : undefined;
    go(current + by);
  };

  const carousel: Carousel = { orientation, count, current, loop, rotating: running, go, step, measure, ...edges };

  return (
    <CarouselContext value={carousel}>
      <div
        role="region"
        aria-roledescription="carousel"
        data-slot="carousel"
        data-orientation={orientation}
        className={cn("relative min-w-0", className)}
        onKeyDown={(event: KeyboardEvent<HTMLDivElement>) => {
          onKeyDown?.(event);
          const target = event.target as HTMLElement;
          if (event.defaultPrevented || target.closest("input, textarea, select, [contenteditable]")) return;
          const rtl = !vertical && getComputedStyle(event.currentTarget).direction === "rtl";
          const back = vertical ? "ArrowUp" : rtl ? "ArrowRight" : "ArrowLeft";
          const forward = vertical ? "ArrowDown" : rtl ? "ArrowLeft" : "ArrowRight";
          if (event.key !== back && event.key !== forward) return;
          event.preventDefault();
          step(event.key === forward ? 1 : -1);
        }}
        onPointerEnter={(event) => {
          onPointerEnter?.(event);
          setHovered(true);
        }}
        onPointerLeave={(event) => {
          onPointerLeave?.(event);
          setHovered(false);
        }}
        onFocus={(event) => {
          onFocus?.(event);
          setFocused(true);
        }}
        onBlur={(event) => {
          onBlur?.(event);
          if (!event.currentTarget.contains(event.relatedTarget)) setFocused(false);
        }}
        {...props}
      >
        <ScrollerContext value={scroller}>{children}</ScrollerContext>
      </div>
    </CarouselContext>
  );
}

/**
 * The strip of slides. It scrolls natively and snaps to each slide. Slides are 12 pixels apart.
 * It is in the tab order, so a keyboard reader can scroll it and use the arrow keys even when the slides hold no controls.
 */
export function CarouselContent({ className, children, onScroll, ...props }: ComponentProps<"div">) {
  const carousel = useCarousel();
  const scroller = useContext(ScrollerContext);
  const vertical = carousel.orientation === "vertical";
  return (
    <div
      ref={scroller}
      data-slot="carousel-content"
      tabIndex={0}
      // A rotating carousel does not announce every slide; one that moves only on request does.
      aria-live={carousel.rotating ? "off" : "polite"}
      onScroll={(event) => {
        onScroll?.(event);
        carousel.measure();
      }}
      className={cn(
        "flex gap-3 overscroll-contain rounded-lg outline-none motion-safe:scroll-smooth [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
        // Inline-size containment keeps the row of slides from widening a grid or flex parent.
        vertical ? "h-full snap-y snap-mandatory flex-col overflow-y-auto" : "snap-x snap-mandatory overflow-x-auto [contain:inline-size]",
        className,
      )}
      {...props}
    >
      {Children.toArray(children).map((child, index) => (
        <SlideIndex key={isValidElement(child) && child.key !== null ? child.key : index} value={index}>
          {child}
        </SlideIndex>
      ))}
    </div>
  );
}

/** One slide. It is as wide as the carousel; give it `basis-[calc(50%-6px)]` to show two at once with the gap. Screen readers hear "Slide 2 of 5". */
export function CarouselItem({ className, ...props }: ComponentProps<"div">) {
  const carousel = useCarousel();
  const index = useContext(SlideIndex);
  return (
    <div
      role="group"
      aria-roledescription="slide"
      aria-label={`${index + 1} of ${carousel.count}`}
      data-slot="carousel-item"
      data-current={index === carousel.current || undefined}
      className={cn("min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start", className)}
      {...props}
    />
  );
}

const ARROW = cn(
  buttonClass({ variant: "outline", size: "icon" }),
  "absolute rounded-[calc(var(--radius)*9999)] border-foreground/20 bg-card/85 shadow-sm disabled:pointer-events-none disabled:opacity-70",
);

/** The button to the slide before. It sits over the start edge; move it with `className`. Disabled on the first slide unless the carousel loops. */
export function CarouselPrevious({ className, onClick, "aria-label": ariaLabel = "Previous slide", ...props }: ComponentProps<"button">) {
  const carousel = useCarousel();
  const vertical = carousel.orientation === "vertical";
  return (
    <button
      type="button"
      data-slot="carousel-previous"
      data-surface="control"
      aria-label={ariaLabel}
      disabled={carousel.count < 2 || (!carousel.loop && carousel.atStart)}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) carousel.step(-1);
      }}
      className={cn(ARROW, vertical ? "top-2 left-1/2 -translate-x-1/2" : "start-2 top-1/2 -translate-y-1/2", className)}
      {...props}
    >
      {vertical ? <ChevronUpIcon size={16} /> : <ChevronLeftIcon size={16} className="rtl:rotate-180" />}
    </button>
  );
}

/** The button to the next slide. It sits over the end edge; move it with `className`. Disabled on the last slide unless the carousel loops. */
export function CarouselNext({ className, onClick, "aria-label": ariaLabel = "Next slide", ...props }: ComponentProps<"button">) {
  const carousel = useCarousel();
  const vertical = carousel.orientation === "vertical";
  return (
    <button
      type="button"
      data-slot="carousel-next"
      data-surface="control"
      aria-label={ariaLabel}
      disabled={carousel.count < 2 || (!carousel.loop && carousel.atEnd)}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) carousel.step(1);
      }}
      className={cn(ARROW, vertical ? "bottom-2 left-1/2 -translate-x-1/2" : "end-2 top-1/2 -translate-y-1/2", className)}
      {...props}
    >
      {vertical ? <ChevronDownIcon size={16} /> : <ChevronRightIcon size={16} className="rtl:rotate-180" />}
    </button>
  );
}

/** One button per slide. The current one is longer as well as darker, and carries `aria-current`. */
export function CarouselDots({ className, "aria-label": ariaLabel = "Choose a slide", ...props }: ComponentProps<"div">) {
  const carousel = useCarousel();
  if (carousel.count < 2) return null;
  return (
    <div
      role="group"
      aria-label={ariaLabel}
      data-slot="carousel-dots"
      data-surface="control"
      className={cn("flex flex-wrap items-center justify-center rounded-[calc(var(--radius)*9999)] border bg-card px-1.5 py-0.5", className)}
      {...props}
    >
      {Array.from({ length: carousel.count }, (_, index) => {
        const current = index === carousel.current;
        return (
          <button
            key={index}
            type="button"
            aria-label={`Slide ${index + 1}`}
            aria-current={current || undefined}
            onClick={() => carousel.go(index)}
            className="group/dot grid size-6 cursor-pointer place-items-center rounded-md focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-ring"
          >
            <span
              className={cn(
                "h-1.5 rounded-[calc(var(--radius)*9999)] transition-[width,background-color] duration-150 ease-out motion-reduce:transition-none",
                current ? "w-4 bg-foreground" : "w-1.5 bg-muted-foreground group-hover/dot:bg-foreground",
              )}
            />
          </button>
        );
      })}
    </div>
  );
}

Files and dependencies

Adds
components/ui/carousel.tsx
Packages
motion
Brings along
ButtonMotion tokensSound engine
Icons
chevron-downchevron-leftchevron-rightchevron-up

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor