Slideshow
Endless carousel that auto-plays, can be dragged and peeks at the next slide.
$npx shadcn@latest add https://framebrick.co/r/slideshow.jsonFrom the Nitip template, see it in context.
"use client";
import { Slideshow } from "@/components/ui/slideshow";
// Demo photos from Unsplash (free under the Unsplash License), served by this site so no request leaves it.
const slides = [
{ title: "Harbour", image: "/demo/slideshow-harbour.webp", alt: "Fishing boats reflected in a still harbour" },
{ title: "Field notes", image: "/demo/slideshow-field-notes.webp", alt: "Ears of wheat against a pale sky" },
{ title: "Long exposure", image: "/demo/slideshow-long-exposure.webp", alt: "Smooth sea under a golden evening sky" },
{ title: "Off season", image: "/demo/slideshow-off-season.webp", alt: "Empty beach pergola under snow" },
];
export default function SlideshowDemo() {
return (
<Slideshow
items={slides}
getKey={(slide) => slide.title}
label="Recent work"
gap={12}
className="w-full max-w-lg"
slideClassName="w-[78%] sm:w-[58%]"
renderItem={(slide) => (
<div className="relative h-48 overflow-hidden rounded-lg bg-muted">
<img src={slide.image} alt={slide.alt} className="size-full object-cover" draggable={false} />
<span className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent p-4 text-sm font-medium text-white">
{slide.title}
</span>
</div>
)}
/>
);
}Examples
No loop
A row with two ends: the arrow at an end fades and is disabled, and a drag past it springs back.
"use client";
import { Slideshow } from "@/components/ui/slideshow";
// Demo photos from Unsplash (free under the Unsplash License), served by this site so no request leaves it.
const posts = [
{ title: "Harbour", image: "/demo/slideshow-harbour.webp", alt: "Fishing boats reflected in a still harbour" },
{ title: "Field notes", image: "/demo/slideshow-field-notes.webp", alt: "Ears of wheat against a pale sky" },
{ title: "Long exposure", image: "/demo/slideshow-long-exposure.webp", alt: "Smooth sea under a golden evening sky" },
{ title: "Off season", image: "/demo/slideshow-off-season.webp", alt: "Empty beach pergola under snow" },
];
/* A row with two ends: the arrow at an end fades and is disabled, and a drag past it springs back. */
export default function SlideshowNoLoopDemo() {
return (
<div className="w-full max-w-md">
<Slideshow
items={posts}
getKey={(post) => post.title}
label="Member stories"
gap={10}
loop={false}
interval={0}
arrows="above"
perView={2}
renderItem={(post) => (
<div className="overflow-hidden rounded-lg">
<img src={post.image} alt={post.alt} className="aspect-[4/3] w-full object-cover" draggable={false} />
<span className="mt-2 block text-sm font-medium">{post.title}</span>
</div>
)}
/>
</div>
);
}<Slideshow items={stories} getKey={(s) => s.slug} label="Member stories" loop={false} interval={0} arrows="above" perView={{ base: 1, sm: 2 }} renderItem={(s) => <StoryCard story={s} />} />Arrows above
Two small arrows in a row above the slides, at the right, always shown; two slides in view.
Inspiration
"use client";
import { Slideshow } from "@/components/ui/slideshow";
// Demo photos from Unsplash (free under the Unsplash License), served by this site so no request leaves it.
const posts = [
{ title: "Harbour", image: "/demo/slideshow-harbour.webp", alt: "Fishing boats reflected in a still harbour" },
{ title: "Field notes", image: "/demo/slideshow-field-notes.webp", alt: "Ears of wheat against a pale sky" },
{ title: "Long exposure", image: "/demo/slideshow-long-exposure.webp", alt: "Smooth sea under a golden evening sky" },
{ title: "Off season", image: "/demo/slideshow-off-season.webp", alt: "Empty beach pergola under snow" },
];
/* Two small arrows in a row above the slides, at the right, always shown; two slides in view. */
export default function SlideshowAboveDemo() {
return (
<div className="w-full max-w-md">
<h3 className="-mb-7 text-sm font-medium">Inspiration</h3>
<Slideshow
items={posts}
getKey={(post) => post.title}
label="Inspiration"
gap={10}
arrows="above"
drag={false}
perView={2}
renderItem={(post) => (
<div className="overflow-hidden rounded-lg">
<img src={post.image} alt={post.alt} className="aspect-[4/3] w-full object-cover" draggable={false} />
<span className="mt-2 block text-sm font-medium">{post.title}</span>
</div>
)}
/>
</div>
);
}<Slideshow items={posts} getKey={(p) => p.slug} label="Inspiration" gap={10} arrows="above" drag={false} perView={{ base: 1, sm: 2 }} renderItem={(p) => <PostCard post={p} />} />Side arrows
One round arrow on each side, shown while the pointer is over the photo or an arrow has the focus; the dots sit over the foot of it.
"use client";
import { Slideshow } from "@/components/ui/slideshow";
// Demo photos from Unsplash (free under the Unsplash License), served by this site so no request leaves it.
const photos = [
{ src: "/demo/media-accordion-strategy.webp", alt: "Glass-walled corridor with a sofa and a floor lamp" },
{ src: "/demo/zoom-card-kestrel.webp", alt: "Calm living room with a low grey sofa" },
{ src: "/demo/media-accordion-build.webp", alt: "Open-plan room with rows of desks and laptops" },
];
/* One round arrow on each side, shown while the pointer is over it or an arrow has the focus (always on a touch screen); the dots sit over the foot of the photo. */
export default function SlideshowSidesDemo() {
return (
<Slideshow
items={photos}
getKey={(photo) => photo.src}
label="Featured homes"
gap={0}
arrows="sides"
dots="inside"
className="w-full max-w-lg"
slideClassName="w-full"
renderItem={(photo) => <img src={photo.src} alt={photo.alt} className="aspect-[16/9] w-full object-cover" draggable={false} />}
/>
);
}<Slideshow items={homes} getKey={(h) => h.slug} label="Featured homes" gap={0} arrows="sides" dots="inside" slideClassName="w-full" renderItem={(h) => <HomePhoto home={h} />} />Card photos
A listing card whose photo turns through three pictures while the card is pointed at, then goes back to the first at once.
"use client";
import { Slideshow } from "@/components/ui/slideshow";
// Demo photos from Unsplash (free under the Unsplash License), served by this site so no request leaves it.
const photos = [
{ src: "/demo/media-accordion-strategy.webp", alt: "Glass-walled corridor with a sofa and a floor lamp" },
{ src: "/demo/zoom-card-kestrel.webp", alt: "Calm living room with a low grey sofa" },
{ src: "/demo/media-accordion-build.webp", alt: "Open-plan room with rows of desks and laptops" },
];
/* Point at the card, or tab into it: its photo turns through three pictures, one every 1.5 s, then goes back to the first at once. */
export default function SlideshowCardPhotosDemo() {
return (
<a href="#" className="group block w-60 rounded-lg outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50">
<Slideshow
items={photos}
getKey={(photo) => photo.src}
label="Photos of the house on Almond Street"
gap={0}
arrows="none"
dots="inside"
run="hover"
hoverTarget=".group"
interval={1500}
className="rounded-lg"
slideClassName="w-full"
renderItem={(photo) => <img src={photo.src} alt={photo.alt} className="aspect-[4/3] w-full object-cover" draggable={false} />}
/>
<span className="mt-2 block text-sm font-medium">14 Almond Street</span>
<span className="block text-sm text-foreground/75">3 bedrooms · Garden</span>
</a>
);
}<a href="/homes/almond-street" className="group block">
<Slideshow items={photos} getKey={(p) => p.src} label="Photos of 14 Almond Street" gap={0} arrows="none" dots="inside" run="hover" hoverTarget=".group" interval={1500} slideClassName="w-full" renderItem={(p) => <Photo photo={p} />} />
<span>14 Almond Street</span>
</a>Row
Small cards, two at a time and more as it widens, that cannot be dragged; every card in view can be read and tabbed to.
"use client";
import { Slideshow } from "@/components/ui/slideshow";
// Demo photos from Unsplash (free under the Unsplash License), served by this site so no request leaves it.
const posts = [
{ title: "Harbour", date: "12 Mar", image: "/demo/slideshow-harbour.webp", alt: "Fishing boats reflected in a still harbour" },
{ title: "Field notes", date: "3 Apr", image: "/demo/slideshow-field-notes.webp", alt: "Ears of wheat against a pale sky" },
{ title: "Long exposure", date: "21 Apr", image: "/demo/slideshow-long-exposure.webp", alt: "Smooth sea under a golden evening sky" },
{ title: "Off season", date: "9 May", image: "/demo/slideshow-off-season.webp", alt: "Empty beach pergola under snow" },
{ title: "Low tide", date: "30 May", image: "/demo/slideshow-harbour.webp", alt: "Fishing boats reflected in a still harbour" },
{ title: "First light", date: "14 Jun", image: "/demo/slideshow-field-notes.webp", alt: "Ears of wheat against a pale sky" },
];
/* A row of small cards, 2 at a time here and 3 or 4 as it widens; it cannot be dragged, and every card in view can be read and tabbed to. */
export default function SlideshowRowDemo() {
return (
<Slideshow
items={posts}
getKey={(post) => post.title}
label="Latest posts"
gap={12}
arrows="none"
drag={false}
perView={{ base: 2, sm: 3, lg: 4 }}
className="w-full max-w-xl"
renderItem={(post) => (
<a href="#" className="block rounded-md outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50">
<img src={post.image} alt={post.alt} className="aspect-[4/3] w-full rounded-md object-cover" draggable={false} />
<span className="mt-2 block text-sm font-medium">{post.title}</span>
<span className="block text-xs text-foreground/75">{post.date}</span>
</a>
)}
/>
);
}<Slideshow
items={posts}
getKey={(p) => p.slug}
label="Latest posts"
gap={30}
arrows="none"
drag={false}
perView={{ base: 1, sm: 2, lg: 4 }}
renderItem={(p) => <PostCard post={p} />}
/>Dots
A row of dots under the frame, one per slide; a dot goes to its slide the shorter way round the loop.
"use client";
import { Slideshow } from "@/components/ui/slideshow";
// Demo photos from Unsplash (free under the Unsplash License), served by this site so no request leaves it.
const slides = [
{ title: "Harbour", image: "/demo/slideshow-harbour.webp", alt: "Fishing boats reflected in a still harbour" },
{ title: "Field notes", image: "/demo/slideshow-field-notes.webp", alt: "Ears of wheat against a pale sky" },
{ title: "Long exposure", image: "/demo/slideshow-long-exposure.webp", alt: "Smooth sea under a golden evening sky" },
{ title: "Off season", image: "/demo/slideshow-off-season.webp", alt: "Empty beach pergola under snow" },
];
/* One dot per slide under the frame; a dot goes to its slide the shorter way round the loop. */
export default function SlideshowDotsDemo() {
return (
<Slideshow
items={slides}
getKey={(slide) => slide.title}
label="Recent work with dots"
gap={12}
arrows="none"
dots
className="w-full max-w-lg"
slideClassName="w-[78%] sm:w-[58%]"
renderItem={(slide) => (
<div className="relative h-48 overflow-hidden rounded-lg bg-muted">
<img src={slide.image} alt={slide.alt} className="size-full object-cover" draggable={false} />
<span className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent p-4 text-sm font-medium text-white">
{slide.title}
</span>
</div>
)}
/>
);
}<Slideshow items={slides} getKey={(s) => s.title} label="Recent work" arrows="none" dots slideClassName="w-[78%] sm:w-[58%]" renderItem={(s) => <SlideCard slide={s} />} />Installation
$ npx shadcn@latest add https://framebrick.co/r/slideshow.json1. Install the dependencies.
npm install motion clsx tailwind-merge2. Add
cn()tolib/utils.ts(skip if shadcn already created it).import { clsx, type ClassValue } from "clsx"; import { extendTailwindMerge } from "tailwind-merge"; /* tailwind-merge must know the site's type scale (globals.css) is a font size, not a text color — otherwise cn("text-h6 text-muted-foreground") drops text-h6. */ const twMerge = extendTailwindMerge({ extend: { classGroups: { "font-size": [{ text: ["display", "h1", "h2", "h3", "h4", "h5", "h6"] }] } }, }); export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }3. Copy the component into
components/ui/slideshow.tsx."use client"; import * as React from "react"; import { animate, motion, useInView, useMotionValue, useReducedMotion, type PanInfo, type Transition } from "motion/react"; import { cn } from "@/lib/utils"; /* * Slideshow — an endless carousel that auto-plays, can be dragged and peeks at the next slide * (from the Nitip "Slideshow"). Three copies of the items let it wrap without a visible seam. * Autoplay pauses while the slideshow is hovered, focused, dragged or scrolled out of view, and never starts for a * visitor who asked for reduced motion — the slides then only move when they move them. `pauseOnHover={false}` lets the * pointer rest on it without stopping it, as the Lookis testimonials do (focus and dragging still pause it). * Arrow keys move one slide; the arrows sit over the bottom right of the frame, or under it on the left, or nowhere * (`arrows`). The slides that are not current are inert as well as aria-hidden, so Tab cannot reach a link inside one. * `dots` adds a row of dots under the frame, one per slide (Catchup's testimonials): the current one at full opacity, * the others at half, each a 24px button round a 10px dot. A dot goes to its slide the shorter way round the loop. * * `perView` (Denzel's slider: 4, 2 and 1 slides at once, 30px apart) shows several slides at a time, a number or one per * width ({ base, sm, md, lg }; each one carries on from the one before it). The slide on show and the ones after it, * as many as are in view, are neither aria-hidden nor inert, so what a visitor can see they can read and Tab to; the others * stay hidden from both. Without a `slideClassName` each slide is (100% - the gaps) / perView wide. The number in view is read * from CSS after layout, so the breakpoints are the slideshow's own width (a container query: sm 576px, md 768px, lg 1024px, so it works in a card or a sidebar) and the markup the server sends never depends on them. When every * slide is in view it holds still: one copy of each, no autoplay, no drag, the arrows do nothing. The default, 1, is the * carousel as it was. `drag={false}` (Denzel's cannot be dragged) turns the pointer drag off; the arrow keys still work. * * Three more options are from Goeboek (and Findit for the first). `arrows="sides"`: one round 40px arrow on each side of the frame, 20px * from the edge, halfway down; where a pointer can hover they show while it is over the slideshow or an arrow has the focus * (Framer: full opacity within 0.1s, gone 0.1 to 0.3s after the pointer leaves; here a 150ms fade, which motion-reduce turns off), * on a touch screen they are always there. A hidden arrow stays in the Tab order and shows when it is reached, so the focus is never * on something unseen. `dots="inside"`: the same row of dots, in a small pill of the page's colour at 80% so they hold 3:1 over a dark * photo, 10px up from the foot of the frame instead of in a row under it. `run="hover"` (Goeboek's property card, whose photo turns * through its pictures only while the card is pointed at: the first step after 1.5s, then every 1.5s on spring 200 / 40 / 1): it stands * on the first slide, steps every `interval` while the pointer or the keyboard focus is on the slideshow, or on the ancestor * `hoverTarget` names (".group", as Marquee's run="hover"), and when they leave it goes back to the first slide at once, with no * movement. `pauseOnHover` is ignored with it. Like autoplay it never runs for a visitor who asked for reduced motion; the dots and * the arrows still move it. * * `arrows="above"` is the Kendi "Inspiration" slideshow: two small round arrows, 25px and 10px apart, in a row above the frame at the * right, always shown (Kendi: 50px above the slides; here the row sits 12px above the frame, which is where a heading usually is). Same * names and bg-background/80 as the others. * * `loop={false}` (Fitbricks' testimonial carousel) makes it a row with two ends: one copy of the slides, no wrapping, the slide on show * stops at the first and at the last (the last one that leaves no empty room when several are in view), and an arrow at an end fades * and is disabled, so it cannot be pressed and is skipped by Tab. Dragging past an end springs back; the dots, the keys and * `run="hover"` work as before, and autoplay stops at the last slide instead of going round. Fitbricks scrolls a native * scroll-snap row by touch; this one is dragged and has arrows, the same code as the looping one. The default, true, is as it was. * * Size the slides with `slideClassName` (e.g. "w-[80%] sm:w-[45%]") and the spacing with `gap`. */ const slide: Transition = { type: "spring", stiffness: 200, damping: 40, mass: 1 }; export type SlideshowProps<T> = { items: T[]; renderItem: (item: T, index: number) => React.ReactNode; getKey: (item: T, index: number) => string; /** Accessible name of the carousel. */ label: string; /** Milliseconds between slides; 0 turns autoplay off. */ interval?: number; /** Stop autoplay while the pointer is over it. False keeps it going (Lookis); focus and dragging still pause it. */ pauseOnHover?: boolean; gap?: number; /** How many slides are in view at once: a number, or one per width of the slideshow itself (sm 576px, md 768px, lg 1024px), each carrying on from the one before. */ perView?: number | { base?: number; sm?: number; md?: number; lg?: number }; /** Wrap round at the ends (default), or stop at the first and the last slide, with the arrow at an end disabled. */ loop?: boolean; /** Whether the pointer can drag it. False leaves the arrows, the dots and the keys. */ drag?: boolean; /** Where the arrows sit: over the bottom right of the frame, under it on the left, one on each side of the frame (shown on hover and focus), a small pair in a row above the frame at the right, or nowhere. */ arrows?: "inside" | "below-left" | "sides" | "above" | "none"; /** A row of dots, one per slide: the current one at full opacity, the others at half. true puts it under the frame; "inside" puts it over the foot of the frame, in a small pill. */ dots?: boolean | "inside"; /** "auto" (default) plays on its own. "hover" stands on the first slide and steps only while the pointer or the focus is on it (or on hoverTarget), then goes back at once. */ run?: "auto" | "hover"; /** With run="hover": a selector for the nearest ancestor whose hover and focus start it (".group"); itself when left out. */ hoverTarget?: string; className?: string; slideClassName?: string; /** Classes for the row of dots: an offset, an alignment, a pill behind them. */ dotsClassName?: string; }; function Arrow({ direction, onClick, className, disabled }: { direction: "left" | "right"; onClick: () => void; className?: string; disabled?: boolean }) { return ( <button type="button" onClick={onClick} aria-label={direction === "left" ? "Previous slide" : "Next slide"} disabled={disabled} className={cn( "grid size-8 cursor-pointer place-items-center rounded-full border bg-background/80 text-foreground shadow-sm backdrop-blur transition-colors hover:bg-accent focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none", disabled !== undefined && "disabled:cursor-default disabled:opacity-40 disabled:hover:bg-background/80", className, )} > <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" className="size-4" aria-hidden> <path d={direction === "left" ? "M10 3.5L5.5 8l4.5 4.5" : "M6 3.5L10.5 8 6 12.5"} /> </svg> </button> ); } /* Each dot is a 24px button (the smallest target WCAG 2.5.8 allows) round a 10px dot. The inactive dots are foreground at 50%, which is 3.2:1 or better against the page in the four sample themes, light and dark (3:1 is what a control needs). */ function Dots({ count, current, onSelect, className }: { count: number; current: number; onSelect: (slide: number) => void; className?: string }) { return ( <div role="group" aria-label="Choose a slide" className={cn("flex items-center", className)}> {Array.from({ length: count }, (_, i) => ( <button key={i} type="button" onClick={() => onSelect(i)} aria-label={`Go to slide ${i + 1}`} aria-current={i === current ? "true" : undefined} className="grid size-6 cursor-pointer place-items-center rounded-full focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none" > <span className={cn("size-2.5 rounded-full bg-foreground", i !== current && "opacity-50")} /> </button> ))} </div> ); } export function Slideshow<T>({ items, renderItem, getKey, label, interval = 5000, pauseOnHover = true, gap = 16, perView, loop = true, drag = true, arrows = "inside", dots = false, run = "auto", hoverTarget, className, slideClassName, dotsClassName, }: SlideshowProps<T>) { const count = items.length; const per = perView === undefined ? null : typeof perView === "number" ? { base: perView } : perView; const perBase = per?.base ?? 1; const perSm = per?.sm ?? perBase; const perMd = per?.md ?? perSm; const perLg = per?.lg ?? perMd; /* How many are in view now: the server and the first render say the base number, the layout effect reads CSS. */ const [visible, setVisible] = React.useState(perBase); const still = per !== null && count <= visible; const slides = still || !loop ? items : [...items, ...items, ...items]; /* The slide the track starts on: the middle copy of three when it loops, the first of one when it does not. */ const firstIndex = loop ? count : 0; const maxIndex = Math.max(0, count - visible); const region = React.useRef<HTMLDivElement>(null); const track = React.useRef<HTMLDivElement>(null); const [indexRaw, setIndexRaw] = React.useState(firstIndex); const index = indexRaw; /* Without a loop the index stops at both ends. */ const setIndex = React.useCallback( (update: number | ((i: number) => number)) => setIndexRaw((i) => { const next = typeof update === "function" ? update(i) : update; return loop ? next : Math.min(Math.max(next, 0), maxIndex); }), [loop, maxIndex], ); const atStart = !loop && index <= 0; const atEnd = !loop && index >= maxIndex; const [step, setStep] = React.useState(0); const [interacting, setInteracting] = React.useState(false); const [dragging, setDragging] = React.useState(false); const inView = useInView(region, { amount: 0.3 }); /* Autoplay is a timer, not a transform, so <MotionConfig reducedMotion="user"> would not stop it: do it here. */ const reduce = useReducedMotion(); const onHover = run === "hover"; /* run="hover": whether the pointer or the focus is on the slideshow (or on its hoverTarget) now. */ const [awake, setAwake] = React.useState(false); const paused = onHover ? !awake || dragging || interval === 0 || Boolean(reduce) || still : interacting || dragging || !inView || interval === 0 || Boolean(reduce) || still; const x = useMotionValue(0); /* Set when the slideshow goes back to its first slide at once, so the next move is a jump and not a glide. */ const jumpBack = React.useRef(false); /* The step the track was last placed for: a different one is a new measurement, not a move. */ const measured = React.useRef(0); React.useLayoutEffect(() => { const el = track.current; if (!el) return; const measure = () => { const first = el.children[0] as HTMLElement | undefined; if (first) setStep(first.offsetWidth + gap); const inView = Number.parseFloat(getComputedStyle(el).getPropertyValue("--per")); if (inView >= 1) setVisible(Math.floor(inView)); }; measure(); const observer = new ResizeObserver(measure); observer.observe(el); return () => observer.disconnect(); }, [gap, perBase, perSm, perMd, perLg]); /* run="hover": wake while the pointer (a mouse or a pen, not a touch) or the focus is on the host, and go back to the first slide when they leave. */ React.useEffect(() => { if (!onHover) return; const element = region.current; const host = (hoverTarget ? element?.closest(hoverTarget) : element) ?? element; if (!host) return; let pointer = false; let focus = false; const update = () => { const on = pointer || focus; setAwake(on); if (!on) { jumpBack.current = true; setIndex(firstIndex); } }; const enter = (event: Event) => { if ((event as PointerEvent).pointerType === "touch") return; pointer = true; update(); }; const leave = () => { pointer = false; update(); }; const focusIn = () => { focus = true; update(); }; const focusOut = (event: Event) => { if (host.contains((event as FocusEvent).relatedTarget as Node | null)) return; focus = false; update(); }; host.addEventListener("pointerenter", enter); host.addEventListener("pointerleave", leave); host.addEventListener("focusin", focusIn); host.addEventListener("focusout", focusOut); return () => { host.removeEventListener("pointerenter", enter); host.removeEventListener("pointerleave", leave); host.removeEventListener("focusin", focusIn); host.removeEventListener("focusout", focusOut); }; }, [onHover, hoverTarget, firstIndex, setIndex]); /* Animate to the current slide, then jump back to the middle copy when the loop runs off either end. A new step (the first measurement, or a resize) puts the track at the slide at once: the slides did not move, the ruler did, so there is nothing to glide. */ React.useEffect(() => { if (!step) return; if (measured.current !== step) { measured.current = step; x.jump(still ? 0 : -index * step); return; } if (still) { x.jump(0); return; } if (jumpBack.current) { jumpBack.current = false; x.jump(-index * step); return; } const controls = animate(x, -index * step, slide); void controls.then(() => { if (loop && (index >= count * 2 || index < count)) { const wrapped = index >= count * 2 ? index - count : index + count; x.jump(-wrapped * step); setIndex(wrapped); } }); return () => controls.stop(); }, [index, step, count, x, still, loop, setIndex]); React.useEffect(() => { if (paused) return; const timer = setTimeout(() => setIndex((i) => i + 1), interval); return () => clearTimeout(timer); }, [index, paused, interval, setIndex]); /* A slide is in reach when it is on show or one of the next ones in view; with every slide in view they all are. */ const inReach = (i: number) => (still ? true : i >= index && i < index + visible); /* The slide on show, and a dot's way to its slide: the shorter way round the loop (the copies on either side are there). */ const current = loop ? ((index % count) + count) % count : Math.min(index, count - 1); function goTo(slide: number) { if (!loop) { setIndex(slide); return; } let delta = slide - current; if (delta > count / 2) delta -= count; else if (delta < -count / 2) delta += count; setIndex((i) => i + delta); } function onDragEnd(_: PointerEvent, info: PanInfo) { setDragging(false); if (still) return; const swiped = Math.abs(info.offset.x) > step * 0.2 || Math.abs(info.velocity.x) > 500; const delta = info.offset.x < 0 ? 1 : -1; /* Past an end there is nowhere to go: the index does not change, so the track has to be sent back by hand. */ if (swiped && (loop || (index + delta >= 0 && index + delta <= maxIndex))) setIndex((i) => i + delta); else animate(x, -index * step, slide); } return ( <div ref={region} role="region" aria-roledescription="carousel" aria-label={label} tabIndex={0} onKeyDown={(e) => { if (still) return; if (e.key === "ArrowRight") setIndex((i) => i + 1); if (e.key === "ArrowLeft") setIndex((i) => i - 1); }} onPointerEnter={(e) => !onHover && pauseOnHover && e.pointerType === "mouse" && setInteracting(true)} onPointerLeave={() => !onHover && pauseOnHover && setInteracting(false)} onFocus={() => !onHover && setInteracting(true)} onBlur={() => !onHover && setInteracting(false)} className={cn( "@container group/slideshow relative overflow-hidden rounded-lg outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50", className, )} > {/* The frame: the arrows that sit over it are anchored here, not to the whole carousel, which can have a row of dots under it. */} {arrows === "above" && ( <div className="mb-3 flex justify-end gap-2.5"> <Arrow direction="left" onClick={() => setIndex((i) => i - 1)} disabled={loop ? undefined : atStart} className="size-[25px]" /> <Arrow direction="right" onClick={() => setIndex((i) => i + 1)} disabled={loop ? undefined : atEnd} className="size-[25px]" /> </div> )} <div className="relative"> <motion.div ref={track} style={{ x, gap, ...(per ? { ["--per-base" as string]: perBase, ["--per-sm" as string]: perSm, ["--per-md" as string]: perMd, ["--per-lg" as string]: perLg, ["--gap" as string]: `${gap}px` } : {}), }} drag={drag && !still ? "x" : false} dragMomentum={false} onDragStart={() => setDragging(true)} onDragEnd={onDragEnd} className={cn( "flex select-none", drag && !still && "cursor-grab active:cursor-grabbing", per && "[--per:var(--per-base)] @xl:[--per:var(--per-sm)] @3xl:[--per:var(--per-md)] @5xl:[--per:var(--per-lg)]", )} > {slides.map((item, i) => ( /* aria-hidden alone leaves a link inside a hidden copy reachable with Tab (axe aria-hidden-focus). */ <div key={`${getKey(item, i % count)}-${i}`} aria-hidden={!inReach(i)} inert={!inReach(i)} className={cn("shrink-0", per && "w-[calc((100%-(var(--per)-1)*var(--gap))/var(--per))]", slideClassName)} > {renderItem(item, i % count)} </div> ))} </motion.div> {arrows === "sides" && ( /* One arrow on each side, halfway down. They show while the pointer is over the slideshow or one has the focus; a touch screen has no hover, so they stay. */ <div className="pointer-events-none absolute inset-x-5 top-1/2 flex -translate-y-1/2 items-center justify-between"> {(["left", "right"] as const).map((direction) => ( <Arrow key={direction} direction={direction} onClick={() => setIndex((i) => i + (direction === "left" ? -1 : 1))} disabled={loop ? undefined : direction === "left" ? atStart : atEnd} className="pointer-events-auto size-10 transition-opacity duration-150 motion-reduce:transition-none [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-focus-within/slideshow:opacity-100 [@media(hover:hover)]:group-hover/slideshow:opacity-100 focus-visible:opacity-100" /> ))} </div> )} {dots === "inside" && count > 1 && ( <div className="pointer-events-none absolute inset-x-0 bottom-2.5 flex justify-center"> <Dots count={count} current={current} onSelect={goTo} className={cn("pointer-events-auto rounded-full bg-background/80 px-1 backdrop-blur-sm", dotsClassName)} /> </div> )} {arrows === "inside" && ( <div className="absolute right-3 bottom-3 flex gap-2.5"> <Arrow direction="left" onClick={() => setIndex((i) => i - 1)} disabled={loop ? undefined : atStart} /> <Arrow direction="right" onClick={() => setIndex((i) => i + 1)} disabled={loop ? undefined : atEnd} /> </div> )} </div> {/* Under the frame: the arrows on the left (when they sit there), the dots in the middle, or on the right beside the arrows. */} {(arrows === "below-left" || (dots === true && count > 1)) && ( <div className={cn("mt-[22px] flex items-center", dots === true && count > 1 ? (arrows === "below-left" ? "justify-between" : "justify-center") : "")}> {arrows === "below-left" && ( <div className="flex gap-2.5"> <Arrow direction="left" onClick={() => setIndex((i) => i - 1)} disabled={loop ? undefined : atStart} /> <Arrow direction="right" onClick={() => setIndex((i) => i + 1)} disabled={loop ? undefined : atEnd} /> </div> )} {dots === true && count > 1 && <Dots count={count} current={current} onSelect={goTo} className={dotsClassName} />} </div> )} </div> ); }
Usage
import { Slideshow } from "@/components/ui/slideshow";
<Slideshow
items={projects}
getKey={(p) => p.slug}
label="Recent work"
slideClassName="w-[78%] sm:w-[58%]"
renderItem={(p) => <ProjectCard project={p} />}
/>
// a dot per slide under the frame (Catchup's testimonials)
<Slideshow items={quotes} getKey={(q) => q.name} label="Testimonials" arrows="none" dots renderItem={(q) => <Quote quote={q} />} />Props
| Prop | Type | Default | Description |
|---|---|---|---|
| items | T[] | — | The slides' data. |
| renderItem | (item, index) => ReactNode | — | Renders one slide. |
| getKey | (item, index) => string | — | Stable key per item. |
| label | string | — | Accessible name of the carousel. |
| interval | number | 5000 | Milliseconds between slides; 0 turns autoplay off. |
| pauseOnHover | boolean | true | Stop autoplay while the pointer is over it. False keeps it going, as the Lookis testimonials do; focus and dragging still pause it. |
| gap | number | 16 | Space between slides, in px. |
| perView | number | { base?, sm?, md?, lg? } | 1 | How many slides are in view at once (Denzel: 4, 2 and 1, 30 px apart). An object gives one number per width of the slideshow itself (sm 576 px, md 768 px, lg 1024 px), each carrying on from the one before. Without slideClassName each slide is (100% - the gaps) / perView wide. All slides in view: it holds still. |
| loop | boolean | true | Wrap round at the ends. false stops at the first and the last slide: one copy of the slides, the arrow at an end fades and is disabled (Fitbricks), and autoplay stops at the last slide. |
| drag | boolean | true | Whether the pointer can drag it. False (Denzel's) leaves the arrows, the dots and the arrow keys. |
| run | "auto" | "hover" | "auto" | auto plays on its own. hover stands on the first slide and steps every interval only while the pointer or the keyboard focus is on the slideshow, or on the ancestor hoverTarget names, then goes back to the first slide at once (Goeboek's property card). pauseOnHover is ignored with it. |
| hoverTarget | string | — | With run="hover": a selector for the nearest ancestor whose hover and focus start it (".group"), the same as Marquee's. Itself when left out. |
| arrows | "inside" | "below-left" | "sides" | "above" | "none" | "inside" | Where the arrows sit: over the bottom right of the frame, under it on the left, one on each side of the frame halfway down (Goeboek, Findit: shown while the pointer is over it or an arrow has the focus, always on a touch screen), a small pair in a row above the frame at the right (Kendi), or nowhere. |
| dots | boolean | "inside" | false | A row of dots, one per slide. true puts it under the frame; "inside" puts it over the foot of the frame, 10 px up, in a small pill of the page colour at 80% so the dots hold 3:1 over a dark photo (Goeboek). Under the frame, one per slide: the current one at full opacity, the others at half. With arrows="below-left" the arrows sit on the left of the same row and the dots on the right. |
| slideClassName | string | — | Width of one slide — under 100% the next slide peeks in. |
| dotsClassName | string | — | Classes for the row of dots: an offset, an alignment, a pill behind them. |
- loop={false} is Fitbricks' testimonial carousel: a row with two ends. One copy of the slides, no wrapping, the slide on show stops at the first and at the last (the last one that leaves no empty room when several are in view), and an arrow at an end fades and is disabled, so it cannot be pressed and Tab skips it. Dragging past an end springs back; the dots, the keys and run="hover" work as before, and autoplay stops at the last slide instead of going round. Fitbricks scrolls a native scroll-snap row by touch and presses the arrow to 0.9; here it is dragged and has the same arrows as the looping one, one code for both. The default, true, is as it was.
- arrows="above" is Kendi's "Inspiration" slideshow: two small round arrows, 25 px and 10 px apart, in a row above the frame at the right, always shown, with two slides in view (one on a phone). Kendi puts them 50 px above the slides, over a heading; here the row sits 12 px above the frame, and a heading above is yours to place. Same names and bg-background/80 as the others.
- arrows="sides" is Goeboek's hero (and Findit's carousel, which keeps them always on): a round 40 px arrow on each side, 20 px from the edge, halfway down, shown while the pointer is over the slideshow or an arrow has the focus (Framer: full opacity within 0.1 s, gone 0.1 to 0.3 s after the pointer leaves; here a 150 ms fade, which motion-reduce turns off). A touch screen has no hover, so they are always there. A hidden arrow stays in the Tab order and shows when it is reached, so the focus is never on something unseen. Same names and bg-background/80 as the others.
- dots="inside" is Goeboek's hero (10 px up from the foot) and property card (8 px dots, 5 px up): the same buttons in the same row, in a small pill of bg-background/80 so the inactive dots keep 3:1 over a dark photo, and no row under the frame. true and false are as they were; dotsClassName still places and styles the row.
- run="hover" is Goeboek's property card, whose photo turns through its pictures only while the card is pointed at (measured: the first step after about 1.5 s, then every 1.5 s, spring 200 / 40 / 1, and back to the first picture at once when the pointer leaves). It stands on the first slide, steps every interval while the pointer (a mouse or a pen) or the keyboard focus is on the slideshow, or on the ancestor hoverTarget names, and goes back to the first slide with no movement when they leave. Like autoplay it never runs for a visitor who asked for reduced motion (Framer's does; this and Goeboek's port stand still): the dots and arrows still move it. The hidden slides stay inert and aria-hidden, so at rest only the first is reachable, and the markup the server sends does not depend on hover.
- perView and drag are Denzel's slider, which already had this component's numbers (5000 ms, spring 200 / 40 / 1, no arrows, no pause on hover): 4, 2 and 1 slides in view, 30 px apart, and a row that cannot be dragged. The slide on show and the ones after it, as many as are in view, are neither aria-hidden nor inert, so three visible cards are read and reached with Tab, which a carousel that hid all but one would not allow. The number in view is read from CSS after layout (the breakpoints are the slideshow's own width, a container query), so the markup the server sends never depends on it; the default, 1, is the carousel as it was. When every slide is in view it holds still: one copy of each, no autoplay, no drag, the arrows do nothing.
- The slideshow is its own named carousel region (role region, aria-roledescription carousel, aria-label from label): a section around it must not carry the same name, or axe reports landmark-unique. Give the section no label, or a different one.
- Autoplay pauses while the slideshow is hovered (unless pauseOnHover is false), focused, dragged or scrolled out of view.
- The Lookis testimonials are this component: interval 4000, spring 200 / 40 / 1, pauseOnHover false, and the arrows over the bottom right of the frame, which is arrows="inside".
- It never auto-plays for a visitor who asked for reduced motion — a timer is not a transform, so MotionConfig would not stop it.
- Drag or swipe to move; ← and → move one slide when the carousel has focus.
- The slides that are not current are inert as well as aria-hidden, so Tab cannot reach a link inside one.
- The dots are Catchup's progress dots on the testimonials' carousel: 10 px dots, the current one at full opacity and the others at 50 %. Catchup draws one per page of its scroll-snap row (3 at 810 px, 5 at 390); this slideshow moves one slide at a time, so it has one dot per slide. A dot goes to its slide the shorter way round the loop, and with one slide there are no dots.
- Each dot is a 24 px button round the 10 px dot (WCAG 2.5.8), named "Go to slide n", with aria-current on the current one, in a group named "Choose a slide". The others are foreground at 50 %: 3.2:1 or better against the page in the four sample themes, light and dark (3.15 on a muted surface at worst), above the 3:1 a control needs. Check your own colours before you rely on it.
AI prompt
Paste into v0, Lovable, Bolt or Claude to rebuild this component in your own project.
Create a React + Tailwind CSS + Motion (motion/react) component called Slideshow — an infinite carousel.
- Render three copies of the items in a flex track; keep an index starting in the middle copy, animate the track's x
motion value to -index * step with a spring (stiffness 200, damping 40, mass 1), and when the index passes either end,
jump silently back into the middle copy (x.jump) and reset the index.
- step = slide width + gap, measured with a ResizeObserver on the track.
- Autoplay every `interval` ms, paused while hovered (mouse only; a pauseOnHover prop, true by default, turns that off),
focused, dragged, or out of view (useInView 0.3).
- drag="x" with dragMomentum false; on drag end, advance if the offset is over 20% of a slide or the velocity over 500,
otherwise spring back.
- Arrow buttons bottom-right: size-8 rounded-full border bg-background/80 shadow-sm.
- Accessibility: role region, aria-roledescription carousel, aria-label, tabIndex 0 with ArrowLeft/ArrowRight,
aria-hidden on slides that are not current.
- A dots prop (false by default) adds a row under the frame, centred, one button per item (none when there is one item):
a size-6 button (a 24px target) round a size-2.5 rounded-full bg-foreground dot, at opacity 50% unless it is the current
slide (index % count). aria-label "Go to slide n", aria-current="true" on the current one, the row a role group named
"Choose a slide". A dot goes to its slide by the shorter way round: delta = slide - current, minus count when it is over
count / 2, plus count when it is under -count / 2, added to the index. With arrows "below-left" the arrows sit on the
left of that row and the dots on the right.
- perView (a number or { base, sm, md, lg }, default 1; each carrying on from the one before) and drag (default true). The track gets inline custom properties --per-base, --per-sm, --per-md, --per-lg and --gap, and the classes [--per:var(--per-base)] @xl:[--per:var(--per-sm)] @3xl:[--per:var(--per-md)] @5xl:[--per:var(--per-lg)] on an @container root, so --per is the number in view at the slideshow's own width. Without a slideClassName each slide is w-[calc((100%-(var(--per)-1)*var(--gap))/var(--per))]. Read --per from getComputedStyle in the same layout effect that measures the step and keep it in state (starting at the base number, so the server markup does not depend on it). Slides from the current index to index + visible - 1 are not aria-hidden or inert. When every slide is in view (count <= visible, with perView set): render one copy, x 0, no autoplay, no drag, arrow keys do nothing. drag false sets drag off and drops the grab cursor.
- loop (default true): false renders one copy of the slides, starts at index 0, clamps the index to 0 and count - visible (every place that changes it goes through one clamped setter), never does the loop jump, and gives the arrows disabled at an end (disabled:opacity-40 disabled:cursor-default); the dots go straight to a slide; autoplay stops at the last slide because the index no longer changes.
- arrows="above": a row (mb-3 flex justify-end gap-2.5) before the frame holding the two arrows at size-[25px]; always shown.
- arrows="sides": a pointer-events-none overlay (absolute inset-x-5, top 50%, -translate-y-1/2, flex justify-between) over the frame holding two size-10 pointer-events-auto round arrows; where hover is available ([@media(hover:hover)]) they are opacity-0 and go to 1 on group-hover and group-focus-within of the root (a group), with a 150ms opacity transition that motion-reduce turns off; on a touch screen they stay visible. They stay focusable.
- dots="inside": the same row of dot buttons in an absolute inset-x-0 bottom-2.5 overlay, centred, inside a rounded-full bg-background/80 px-1 pill (backdrop-blur-sm); no row under the frame (only dots === true draws that one).
- run ("auto" | "hover", default "auto") and hoverTarget: with hover the slideshow stands on the first slide and the autoplay timer only runs while the pointer (not touch) or the keyboard focus is on the root or on the ancestor root.closest(hoverTarget); pauseOnHover is ignored. When they leave, set the index back to the first slide and jump the track there (x.jump, a flag the animate effect reads) with no movement. Reduced motion never autoplays.

















