Carousel
Slides in a row or a column that you drag, swipe, scroll or step through, snapping into place. No library: it is the browser's own scroll snapping.
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel";
import { Card, CardContent } from "@/components/ui/card";
export default function CarouselDemo() {
return (
<Carousel className="w-full max-w-xs" aria-label="Pages">
<CarouselContent>
{Array.from({ length: 5 }, (_, i) => (
<CarouselItem key={i}>
<div className="p-1">
<Card seed={`car-${i}`}>
<CardContent className="flex aspect-square items-center justify-center">
<span className="text-5xl font-bold">{i + 1}</span>
</CardContent>
</Card>
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious seed="car-prev" />
<CarouselNext seed="car-next" />
</Carousel>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ carousel"use client";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ComponentProps, type KeyboardEvent, type RefObject } from "react";
import { cn } from "@/lib/utils";
import { InkGlyph } from "@/lib/ink-glyphs";
import { Button } from "@/components/ui/button";
// Slides in a row (or a column) that you drag, swipe, scroll or step through.
// It's the browser's own scroll snapping underneath, so touch, trackpads and
// keyboards behave as they do everywhere, and no carousel library is needed.
type Event = "select" | "reInit";
/** What `setApi` hands you: the part of Embla's API that most carousels use. */
export type CarouselApi = {
scrollPrev: () => void;
scrollNext: () => void;
scrollTo: (index: number) => void;
canScrollPrev: () => boolean;
canScrollNext: () => boolean;
selectedScrollSnap: () => number;
scrollSnapList: () => number[];
on: (event: Event, callback: (api: CarouselApi) => void) => CarouselApi;
off: (event: Event, callback: (api: CarouselApi) => void) => CarouselApi;
};
type CarouselOptions = {
/** Which edge of the row the chosen slide rests against. */
align?: "start" | "center" | "end";
/** Step past the last slide to the first, and back. */
loop?: boolean;
};
type CarouselContextValue = {
scroller: RefObject<HTMLDivElement | null>;
orientation: "horizontal" | "vertical";
api: CarouselApi;
canPrev: boolean;
canNext: boolean;
};
const CarouselContext = createContext<CarouselContextValue | null>(null);
function useCarousel() {
const context = useContext(CarouselContext);
if (!context) throw new Error("Carousel parts must be used inside <Carousel>.");
return context;
}
const smooth = () => (typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth");
/** The slides, their order and where each starts along the scroller. */
function snapsOf(scroller: HTMLElement | null, vertical: boolean, align: NonNullable<CarouselOptions["align"]>) {
const slides = Array.from(scroller?.querySelectorAll<HTMLElement>("[data-slot=carousel-item]") ?? []);
if (!scroller) return [];
const size = vertical ? scroller.clientHeight : scroller.clientWidth;
const max = (vertical ? scroller.scrollHeight : scroller.scrollWidth) - size;
const origin = vertical ? scroller.getBoundingClientRect().top : scroller.getBoundingClientRect().left;
return slides.map((slide) => {
const box = slide.getBoundingClientRect();
const start = (vertical ? box.top : box.left) - origin + (vertical ? scroller.scrollTop : scroller.scrollLeft);
const length = vertical ? box.height : box.width;
const at = align === "start" ? start : align === "center" ? start - (size - length) / 2 : start - (size - length);
return Math.min(Math.max(at, 0), Math.max(max, 0));
});
}
/**
* Slides to look through. Drag or swipe, use the arrow keys, or step with
* CarouselPrevious and CarouselNext. `setApi` gives you the controls, for
* dots or a "3 of 5".
*/
function Carousel({
orientation = "horizontal",
opts,
setApi,
className,
children,
onKeyDownCapture,
...props
}: ComponentProps<"div"> & { orientation?: "horizontal" | "vertical"; opts?: CarouselOptions; setApi?: (api: CarouselApi) => void }) {
const scroller = useRef<HTMLDivElement>(null);
const vertical = orientation === "vertical";
const align = opts?.align ?? "start";
const loop = opts?.loop ?? false;
const [edges, setEdges] = useState({ start: true, end: true });
const config = useRef({ vertical, align, loop });
const listeners = useRef<Record<Event, Set<(api: CarouselApi) => void>>>({ select: new Set(), reInit: new Set() });
const state = useRef({ selected: 0, snaps: [] as number[], start: true, end: true });
useEffect(() => {
config.current = { vertical, align, loop };
}, [vertical, align, loop]);
// One api for the carousel's life: it reads the refs when it is called.
const [api] = useState<CarouselApi>(() => {
const scrollTo = (index: number) => {
const el = scroller.current;
const { vertical: v, align: a } = config.current;
const snaps = snapsOf(el, v, a);
if (!el || !snaps.length) return;
const target = snaps[Math.min(Math.max(index, 0), snaps.length - 1)];
el.scrollTo(v ? { top: target, behavior: smooth() } : { left: target, behavior: smooth() });
};
const self: CarouselApi = {
scrollTo,
scrollPrev: () => {
const { selected: at, snaps } = state.current;
if (at > 0) scrollTo(at - 1);
else if (config.current.loop && snaps.length) scrollTo(snaps.length - 1);
},
scrollNext: () => {
const { selected: at, snaps } = state.current;
if (at < snaps.length - 1) scrollTo(at + 1);
else if (config.current.loop) scrollTo(0);
},
canScrollPrev: () => config.current.loop || !state.current.start,
canScrollNext: () => config.current.loop || !state.current.end,
selectedScrollSnap: () => state.current.selected,
scrollSnapList: () => state.current.snaps,
on: (event, callback) => (listeners.current[event].add(callback), self),
off: (event, callback) => (listeners.current[event].delete(callback), self),
};
return self;
});
const measure = useCallback(() => {
const el = scroller.current;
if (!el) return;
const snaps = snapsOf(el, vertical, align);
const at = vertical ? el.scrollTop : el.scrollLeft;
const max = (vertical ? el.scrollHeight - el.clientHeight : el.scrollWidth - el.clientWidth) - 1;
let nearest = 0;
snaps.forEach((snap, i) => {
if (Math.abs(snap - at) < Math.abs(snaps[nearest] - at)) nearest = i;
});
// At the very end the last slide counts as chosen, even if it can't reach its own snap.
if (snaps.length && at >= max) nearest = snaps.length - 1;
const changed = nearest !== state.current.selected;
state.current = { selected: nearest, snaps, start: at <= 1, end: at >= max };
setEdges((now) => (now.start === state.current.start && now.end === state.current.end ? now : { start: state.current.start, end: state.current.end }));
if (changed) listeners.current.select.forEach((fn) => fn(api));
}, [vertical, align, api]);
useEffect(() => {
const el = scroller.current;
if (!el) return;
let frame = 0;
const onScroll = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(measure);
};
measure();
listeners.current.reInit.forEach((fn) => fn(api));
el.addEventListener("scroll", onScroll, { passive: true });
const resize = new ResizeObserver(onScroll);
resize.observe(el);
for (const slide of el.querySelectorAll("[data-slot=carousel-item]")) resize.observe(slide);
return () => {
cancelAnimationFrame(frame);
el.removeEventListener("scroll", onScroll);
resize.disconnect();
};
}, [measure, api]);
useEffect(() => {
setApi?.(api);
}, [api, setApi]);
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
onKeyDownCapture?.(event);
if (event.defaultPrevented) return;
const [back, forward] = vertical ? ["ArrowUp", "ArrowDown"] : ["ArrowLeft", "ArrowRight"];
if (event.key === back) {
event.preventDefault();
api.scrollPrev();
} else if (event.key === forward) {
event.preventDefault();
api.scrollNext();
}
};
const value = useMemo(() => ({ scroller, orientation, api, canPrev: loop || !edges.start, canNext: loop || !edges.end }), [orientation, api, loop, edges]);
return (
<CarouselContext value={value}>
<div role="region" aria-roledescription="carousel" data-slot="carousel" className={cn("relative", className)} onKeyDownCapture={onKeyDown} {...props}>
{children}
</div>
</CarouselContext>
);
}
function CarouselContent({ className, ...props }: ComponentProps<"div">) {
const { scroller, orientation } = useCarousel();
const vertical = orientation === "vertical";
return (
<div
ref={scroller}
data-slot="carousel-viewport"
// The scrolling box can be tabbed to, so a keyboard can scroll it.
tabIndex={0}
className={cn(
"outline-none focus-visible:outline-solid focus-visible:outline-[1.5px] focus-visible:outline-offset-2 focus-visible:outline-ring overflow-auto overscroll-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
vertical ? "snap-y snap-mandatory" : "snap-x snap-mandatory",
vertical && "max-h-[inherit]",
)}
>
<div data-slot="carousel-content" className={cn("flex", vertical ? "-mt-4 flex-col" : "-ml-4", className)} {...props} />
</div>
);
}
function CarouselItem({ className, ...props }: ComponentProps<"div">) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn("min-w-0 shrink-0 grow-0 basis-full snap-start", orientation === "horizontal" ? "pl-4" : "pt-4", className)}
{...props}
/>
);
}
function CarouselPrevious({ className, variant = "outline", size = "icon-sm", ...props }: ComponentProps<typeof Button>) {
const { orientation, api, canPrev } = useCarousel();
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn("absolute", orientation === "horizontal" ? "top-1/2 -left-12 -translate-y-1/2 max-sm:left-2" : "-top-12 left-1/2 -translate-x-1/2 rotate-90", className)}
disabled={!canPrev}
onClick={() => api.scrollPrev()}
{...props}
>
<InkGlyph name="arrow-right" className="-scale-x-100 rtl:scale-x-100" />
<span className="sr-only">Previous slide</span>
</Button>
);
}
function CarouselNext({ className, variant = "outline", size = "icon-sm", ...props }: ComponentProps<typeof Button>) {
const { orientation, api, canNext } = useCarousel();
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn("absolute", orientation === "horizontal" ? "top-1/2 -right-12 -translate-y-1/2 max-sm:right-2" : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90", className)}
disabled={!canNext}
onClick={() => api.scrollNext()}
{...props}
>
<InkGlyph name="arrow-right" className="rtl:-scale-x-100" />
<span className="sr-only">Next slide</span>
</Button>
);
}
export { Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext };Usage
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel"
<Carousel>
<CarouselContent>
<CarouselItem>…</CarouselItem>
<CarouselItem>…</CarouselItem>
</CarouselContent>
<CarouselPrevious />
<CarouselNext />
</Carousel>Examples
Sizes
Slides narrower than the row, several in view at once.
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel";
import { Card, CardContent } from "@/components/ui/card";
export default function CarouselSizes() {
return (
<Carousel opts={{ align: "start" }} className="w-full max-w-sm" aria-label="Sketches">
<CarouselContent>
{Array.from({ length: 7 }, (_, i) => (
<CarouselItem key={i} className="basis-1/2 lg:basis-1/3">
<div className="p-1">
<Card seed={`cars-${i}`}>
<CardContent className="flex aspect-square items-center justify-center p-4">
<span className="text-3xl font-bold">{i + 1}</span>
</CardContent>
</Card>
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious seed="cars-prev" />
<CarouselNext seed="cars-next" />
</Carousel>
);
}Vertical
A column of slides, with the arrows above and below.
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel";
import { Card, CardContent } from "@/components/ui/card";
export default function CarouselVertical() {
return (
<div className="py-12">
<Carousel orientation="vertical" className="w-full max-w-xs max-h-48" aria-label="Notes">
<CarouselContent className="h-48">
{Array.from({ length: 4 }, (_, i) => (
<CarouselItem key={i} className="basis-full">
<div className="p-1">
<Card seed={`carv-${i}`}>
<CardContent className="flex h-32 items-center justify-center">
<span className="text-3xl font-bold">{i + 1}</span>
</CardContent>
</Card>
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious seed="carv-prev" />
<CarouselNext seed="carv-next" />
</Carousel>
</div>
);
}With the API
setApi hands you the controls: dots, a position, a loop.
"use client";
import { useEffect, useState } from "react";
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, type CarouselApi } from "@/components/ui/carousel";
import { Card, CardContent } from "@/components/ui/card";
export default function CarouselApiExample() {
const [api, setApi] = useState<CarouselApi>();
const [current, setCurrent] = useState(0);
const [count, setCount] = useState(0);
useEffect(() => {
if (!api) return;
const update = () => {
setCount(api.scrollSnapList().length);
setCurrent(api.selectedScrollSnap());
};
update();
api.on("select", update).on("reInit", update);
return () => void api.off("select", update).off("reInit", update);
}, [api]);
return (
<div className="mx-auto w-full max-w-xs">
<Carousel setApi={setApi} opts={{ loop: true }} aria-label="Slides">
<CarouselContent>
{Array.from({ length: 5 }, (_, i) => (
<CarouselItem key={i}>
<div className="p-1">
<Card seed={`carapi-${i}`}>
<CardContent className="flex aspect-video items-center justify-center">
<span className="text-4xl font-bold">{i + 1}</span>
</CardContent>
</Card>
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious seed="carapi-prev" />
<CarouselNext seed="carapi-next" />
</Carousel>
<div className="flex items-center justify-center gap-2 pt-4" role="group" aria-label="Choose a slide">
{Array.from({ length: count }, (_, i) => (
<button
key={i}
type="button"
aria-label={`Go to slide ${i + 1}`}
aria-current={i === current}
onClick={() => api?.scrollTo(i)}
className="group flex size-6 cursor-pointer items-center justify-center"
>
<span className={`size-2.5 rounded-full border border-ink-line transition-colors ${i === current ? "bg-ink" : "bg-transparent"}`} />
</button>
))}
</div>
</div>
);
}API reference
- orientationdefault
"horizontal" "horizontal" | "vertical"Which way the slides run.
- opts
{ align?: 'start' | 'center' | 'end'; loop?: boolean }Where the chosen slide rests, and whether the ends wrap round.
- setApi
(api: CarouselApi) => voidCalled with scrollPrev, scrollNext, scrollTo, canScrollPrev, canScrollNext, selectedScrollSnap, scrollSnapList, on and off.
- CarouselItem className
stringSet the slide's width: basis-1/2, basis-1/3.