Carousel

Looping image carousel with arrows, dots, swipe and per-slide captions.

Installation

CLI

pnpm dlx shadcn@latest add @riff/carousel

Manual

  1. Copy the component

    Save this as components/ui/carousel.tsx:

    'use client';
    import {
      useId,
      useRef,
      useState,
      type KeyboardEvent,
      type TouchEvent,
    } from 'react';
    import './carousel.css';
    
    export type CarouselSlide = { src: string; alt: string; caption?: string };
    
    // A horizontal swipe shorter than this is a tap or a scroll.
    const SWIPE_PX = 50;
    
    function Chevron({ direction }: { direction: 'previous' | 'next' }) {
      return (
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <path d={direction === 'previous' ? 'm15 19-7-7 7-7' : 'm9 5 7 7-7 7'} />
        </svg>
      );
    }
    
    /**
     * Images in one frame that loops in either direction: arrows on hover or
     * focus, dots to jump, swipe on touch and the arrow keys when focused. Each
     * slide's caption shows beside the dots.
     */
    export function Carousel({
      slides,
      label = 'Image gallery',
      aspectRatio = '16 / 10',
    }: {
      slides: readonly CarouselSlide[];
      label?: string;
      /** The frame's ratio; slides are contained inside it. */
      aspectRatio?: string;
    }) {
      const captionId = useId();
      // `position` counts every step taken, so the track can keep sliding the
      // same way past either end; slides are recycled by whole laps.
      const [{ position, instant, direction }, setSlide] = useState({
        position: 0,
        instant: true,
        direction: -1,
      });
      const count = slides.length;
      const index = count ? ((position % count) + count) % count : 0;
      const lap = direction > 0 ? Math.floor : Math.ceil;
      const touch = useRef<number | null>(null);
    
      const shift = (step: -1 | 1, keyboard = false) =>
        setSlide((current) => ({
          position: current.position + step,
          instant: keyboard || count < 2,
          direction: step,
        }));
      const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
        if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
        event.preventDefault();
        shift(event.key === 'ArrowLeft' ? -1 : 1, true);
      };
      const onTouchEnd = (event: TouchEvent<HTMLDivElement>) => {
        const end = event.changedTouches[0]?.clientX;
        if (
          touch.current !== null &&
          end !== undefined &&
          Math.abs(touch.current - end) > SWIPE_PX
        )
          shift(touch.current > end ? 1 : -1);
        touch.current = null;
      };
    
      if (!count) return null;
      const caption = slides[index]?.caption;
      return (
        <section
          className="riff-carousel"
          aria-roledescription="carousel"
          aria-label={label}
        >
          <div
            className="riff-carousel-window"
            aria-describedby={caption ? captionId : undefined}
            // The arrow keys step slides while an arrow button has focus.
            onKeyDownCapture={onKeyDown}
            onTouchStart={(event) => {
              touch.current = event.touches[0]?.clientX ?? null;
            }}
            onTouchEnd={onTouchEnd}
            onTouchCancel={() => {
              touch.current = null;
            }}
          >
            <div
              className="riff-carousel-track"
              data-instant={instant ? '' : undefined}
              style={{ transform: `translateX(${-position * 100}%)` }}
            >
              {slides.map((slide, slideIndex) => {
                const laps = lap((position - slideIndex) / count);
                return (
                  <div
                    // oxlint-disable-next-line react/no-array-index-key -- Slides are positional and may repeat an image.
                    key={`${slide.src}:${slideIndex}`}
                    className="riff-carousel-slide"
                    role="group"
                    aria-roledescription="slide"
                    aria-label={`${slideIndex + 1} of ${count}`}
                    aria-hidden={slideIndex !== index}
                    inert={slideIndex !== index}
                    style={{
                      aspectRatio,
                      // Keep the outgoing slide on the side the track came from.
                      translate: laps ? `${laps * count * 100}%` : undefined,
                    }}
                  >
                    <img
                      className="riff-carousel-image"
                      src={slide.src}
                      alt={slide.alt}
                      draggable={false}
                      loading={slideIndex === 0 ? 'eager' : 'lazy'}
                    />
                  </div>
                );
              })}
            </div>
            {count > 1 && (
              <>
                <button
                  type="button"
                  className="riff-carousel-arrow"
                  data-side="previous"
                  aria-label="Previous slide"
                  onClick={() => shift(-1)}
                >
                  <Chevron direction="previous" />
                </button>
                <button
                  type="button"
                  className="riff-carousel-arrow"
                  data-side="next"
                  aria-label="Next slide"
                  onClick={() => shift(1)}
                >
                  <Chevron direction="next" />
                </button>
              </>
            )}
          </div>
          <div className="riff-carousel-footer">
            {caption && (
              <p id={captionId} className="riff-carousel-caption">
                {caption}
              </p>
            )}
            {count > 1 && (
              <div className="riff-carousel-dots">
                {slides.map((slide, slideIndex) => (
                  <button
                    // oxlint-disable-next-line react/no-array-index-key -- Dots are positional.
                    key={`${slide.src}:${slideIndex}`}
                    type="button"
                    className="riff-carousel-dot"
                    aria-label={`Go to slide ${slideIndex + 1}`}
                    aria-current={slideIndex === index ? 'true' : undefined}
                    onClick={(event) =>
                      setSlide({
                        position: position + slideIndex - index,
                        instant: event.detail === 0,
                        direction: slideIndex >= index ? 1 : -1,
                      })
                    }
                  />
                ))}
              </div>
            )}
          </div>
        </section>
      );
    }
  2. Copy its styles

    Save this beside it as carousel.css:

    /* Host roles first, system colours after: the component reads your theme
       when it has these properties and stays legible when it does not. */
    @layer components {
      .riff-carousel {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        width: 100%;
      }
      .riff-carousel-window {
        position: relative;
        overflow: hidden;
        border: 1px solid var(--color-border, GrayText);
        border-radius: 0.75rem;
        background-color: var(--color-muted, Canvas);
        &:focus-visible {
          outline: 2px solid var(--color-ring, Highlight);
          outline-offset: 2px;
        }
      }
      .riff-carousel-track {
        display: flex;
      }
      @media (prefers-reduced-motion: no-preference) {
        .riff-carousel-track:not([data-instant]) {
          transition: transform 500ms cubic-bezier(0.4, 0, 0.2, 1);
        }
      }
      .riff-carousel-slide {
        position: relative;
        width: 100%;
        flex-shrink: 0;
        overflow: hidden;
      }
      .riff-carousel-image {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        object-fit: contain;
        user-select: none;
      }
      /* 32px rounded squares on a dark wash, shown on hover or focus. */
      .riff-carousel-arrow {
        position: absolute;
        z-index: 1;
        top: 50%;
        display: grid;
        width: 2rem;
        height: 2rem;
        place-items: center;
        border: 0;
        border-radius: 0.375rem;
        padding: 0;
        background-color: rgb(0 0 0 / 55%);
        color: #fff;
        cursor: pointer;
        opacity: 0;
        translate: 0 -50%;
        backdrop-filter: blur(8px);
        transition:
          opacity 150ms cubic-bezier(0.4, 0, 0.2, 1),
          background-color 150ms cubic-bezier(0.4, 0, 0.2, 1);
        &[data-side='previous'] {
          left: 0.75rem;
        }
        &[data-side='next'] {
          right: 0.75rem;
        }
        &:focus-visible {
          opacity: 1;
          outline: 2px solid var(--color-ring, Highlight);
          outline-offset: 2px;
        }
        & > svg {
          width: 1.25rem;
          height: 1.25rem;
        }
      }
      .riff-carousel-footer {
        display: flex;
        align-items: flex-start;
        gap: 0.75rem;
      }
      .riff-carousel-caption {
        margin: 0;
        color: var(--color-muted-foreground, GrayText);
        font-size: 0.875rem;
        line-height: 1.5;
      }
      .riff-carousel-dots {
        display: flex;
        max-inline-size: 50%;
        flex: none;
        flex-wrap: wrap;
        justify-content: flex-end;
        margin-inline-start: auto;
      }
      /* 24px targets around 4px dots; the current dot stretches to 12px. */
      .riff-carousel-dot {
        display: grid;
        width: 0.75rem;
        height: 1.5rem;
        place-items: center;
        border: 0;
        padding: 0;
        background: none;
        cursor: pointer;
        &::before {
          content: '';
          width: 4px;
          height: 4px;
          border-radius: 999px;
          background-color: var(--color-muted-foreground, GrayText);
          transition:
            width 200ms cubic-bezier(0.4, 0, 0.2, 1),
            background-color 200ms cubic-bezier(0.4, 0, 0.2, 1);
        }
        &[aria-current='true'] {
          width: 1.25rem;
          &::before {
            width: 0.75rem;
            background-color: var(--color-foreground, CanvasText);
          }
        }
        &:focus-visible {
          border-radius: 0.25rem;
          outline: 2px solid var(--color-ring, Highlight);
        }
      }
      @media (hover: hover) {
        .riff-carousel-window:hover .riff-carousel-arrow {
          opacity: 1;
        }
        .riff-carousel-arrow:hover {
          background-color: rgb(0 0 0 / 75%);
        }
        .riff-carousel-dot:not([aria-current='true']):hover::before {
          background-color: var(--color-foreground, CanvasText);
        }
      }
      /* Touch screens have no hover, so arrows stay visible. */
      @media (hover: none) {
        .riff-carousel-arrow {
          opacity: 1;
        }
      }
      @media (prefers-reduced-motion: reduce) {
        .riff-carousel-arrow,
        .riff-carousel-dot::before {
          transition: none;
        }
      }
    }

Usage

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

<Carousel
  slides={[
    { src: '/one.webp', alt: 'The dashboard' },
    { src: '/two.webp', alt: 'The settings page' },
  ]}
/>;

It loops in both directions without rewinding. Arrows show on hover and focus, the dots jump to a slide, touch swipes, and the arrow keys step while an arrow button has focus. Slides are contained in the frame, so mixed sizes stay whole.

Props

PropTypeDefaultDescription
slidesCarouselSlide[]Each src, alt and optional caption.
labelstring'Image gallery'Names the carousel.
aspectRatiostring'16 / 10'The frame’s ratio.