Components
Carousel
A row of slides to move through with buttons, dots, swipe and the keyboard, and optionally on its own.
Introduction
Carousel shows a few slides at a time from a longer set: featured products, screenshots, testimonials, steps of an onboarding. It is built on a scroll container that snaps, so touch swipes, trackpad flicks and the wheel work as the browser does them, and every gesture comes to rest on a slide.
- Any content in a slide. Show one at a time, several with
slidesPerView, or let the next one peek in with a fraction. - Previous and Next buttons, and dots. Each is a part you place, so leave out what you do not need.
- The arrow keys, Home and End move between slides. Slides are named "2 of 6" for screen readers.
- Horizontal or vertical, looping or stopping at the ends, and optional autoplay that pauses on hover and focus and stays off for people who prefer reduced motion.
- Uncontrolled, or controlled with
indexandonIndexChange.
The slides scroll; they do not clone. With loop the buttons wrap around to the other end instead of scrolling forever.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Carousel uses Button for its previous and next buttons.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxAdd Button first (see its Manual installation), then follow the steps below.
Manual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles and the context
src/types/carousel-styles.tsShow code
import { tv } from "tailwind-variants";
// Styles for Carousel. The content is a scroll container that snaps: the
// browser does the swiping, the flinging and the stopping on a slide. The
// number of slides in view and the gap come from the `--slides` and `--gap`
// variables the root sets, so a slide is sized with plain CSS.
export const carouselStyles = tv({
slots: {
root: "relative",
content: [
"flex size-full snap-mandatory outline-none",
"[scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
"gap-(--gap)",
],
item: "min-w-0 shrink-0 grow-0 basis-[calc((100%-(var(--slides)-1)*var(--gap))/var(--slides))]",
control: "absolute z-10 shadow-sm",
dots: "flex items-center justify-center gap-2",
dot: [
"relative size-2 rounded-full bg-fg/25 outline-none transition-[background-color,width]",
"after:absolute after:top-1/2 after:left-1/2 after:size-6 after:-translate-x-1/2 after:-translate-y-1/2",
"hover:bg-fg/50",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
"aria-[current=true]:w-5 aria-[current=true]:bg-fg",
],
},
variants: {
orientation: {
horizontal: {
content: "snap-x flex-row overflow-x-auto overflow-y-hidden",
item: "snap-start",
},
vertical: {
content: "snap-y flex-col overflow-y-auto overflow-x-hidden",
item: "snap-start",
dots: "flex-col",
dot: "aria-[current=true]:h-5 aria-[current=true]:w-2",
},
},
},
defaultVariants: { orientation: "horizontal" },
});src/types/carousel-context.tsShow code
import { createContext, type RefObject, useContext } from "react";
export interface CarouselContextValue {
orientation: "horizontal" | "vertical";
/** The scroll container, set by CarouselContent. */
viewportRef: RefObject<HTMLDivElement | null>;
/** Index of the slide the carousel is showing (the first one in view). */
current: number;
/** How many places the carousel can stop at. Zero until it is measured. */
pages: number;
canPrev: boolean;
canNext: boolean;
/** Whether the ends connect: going past the last slide returns to the first. */
loop: boolean;
isAutoPlaying: boolean;
scrollPrev: () => void;
scrollNext: () => void;
scrollTo: (index: number) => void;
/** Measure again. CarouselContent calls it on scroll. */
update: () => void;
}
const CarouselContext = createContext<CarouselContextValue | null>(null);
export const CarouselProvider = CarouselContext.Provider;
/** The enclosing Carousel's state, or an error outside of one. */
export function useCarousel() {
const context = useContext(CarouselContext);
if (!context) {
throw new Error("Carousel parts must be used inside a <Carousel>.");
}
return context;
}
/** Position of a slide inside its CarouselContent, for its accessible name. */
export const CarouselSlideContext = createContext<{
index: number;
total: number;
} | null>(null);2. Add the Carousel file
src/components/ui/carousel/carousel.tsxShow code
"use client";
import {
Children,
type KeyboardEvent,
type ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
ChevronUpIcon,
} from "@/components/icons";
import { Button, type ButtonProps } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import {
CarouselProvider,
CarouselSlideContext,
useCarousel,
} from "@/types/carousel-context";
import { carouselStyles } from "@/types/carousel-styles";
export interface CarouselProps {
/** A `CarouselContent`, and the buttons and dots you want around it. */
children: ReactNode;
orientation?: "horizontal" | "vertical";
/**
* How many slides are in view. A fraction such as `1.3` lets the next slide
* peek in. Defaults to `1`.
*/
slidesPerView?: number;
/** Space between slides, in pixels. Defaults to `16`. */
gap?: number;
/** Connect the ends: Next on the last slide goes back to the first, and Previous on the first goes to the last. */
loop?: boolean;
/**
* Move on by itself, every so many milliseconds (`true` is 5000). It pauses
* while the pointer is over the carousel or focus is inside it, and it does
* not run when the user prefers reduced motion. Always goes back to the
* start after the last slide.
*/
autoPlay?: boolean | number;
/** The slide to show, for a controlled carousel. */
index?: number;
/** The slide to start on, for an uncontrolled carousel. */
defaultIndex?: number;
/** Called when the carousel settles on another slide, by any means. */
onIndexChange?: (index: number) => void;
/** Names the carousel for screen readers, for example "Featured products". */
"aria-label"?: string;
className?: string;
}
const prefersReducedMotion = () =>
typeof window !== "undefined" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
/**
* A row (or column) of slides to move through one at a time, with buttons,
* dots, keyboard support and optional autoplay. The slides sit in a scroll
* container that snaps, so swiping, flinging and trackpads work natively and
* the browser stops them on a slide. Compose it from `CarouselContent`,
* `CarouselItem`, `CarouselPrevious`, `CarouselNext` and `CarouselDots`.
*
* Give it a width, and for `orientation="vertical"` a height too.
*
* @example
* <Carousel aria-label="Featured" className="w-full max-w-md">
* <CarouselContent>
* <CarouselItem>One</CarouselItem>
* <CarouselItem>Two</CarouselItem>
* </CarouselContent>
* <CarouselPrevious />
* <CarouselNext />
* </Carousel>
*/
export function Carousel({
children,
orientation = "horizontal",
slidesPerView = 1,
gap = 16,
loop = false,
autoPlay = false,
index,
defaultIndex = 0,
onIndexChange,
className,
...props
}: CarouselProps) {
const viewportRef = useRef<HTMLDivElement>(null);
const [current, setCurrent] = useState(0);
const [pages, setPages] = useState(0);
const [canPrev, setCanPrev] = useState(false);
const [canNext, setCanNext] = useState(false);
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
const horizontal = orientation === "horizontal";
const interval = autoPlay === true ? 5000 : autoPlay || 0;
const isAutoPlaying = interval > 0;
// Where every slide starts, and how far the container can scroll.
const measure = useCallback(() => {
const el = viewportRef.current;
if (!el) return null;
const box = el.getBoundingClientRect();
const position = horizontal ? el.scrollLeft : el.scrollTop;
const max = horizontal
? el.scrollWidth - el.clientWidth
: el.scrollHeight - el.clientHeight;
const offsets = Array.from(el.children).map((child) => {
const rect = child.getBoundingClientRect();
return (
(horizontal ? rect.left - box.left : rect.top - box.top) + position
);
});
// A slide is a place to stop only if the container can scroll that far.
const stops = offsets.filter((offset) => offset <= max + 1);
return {
el,
position,
max,
stops,
pages: offsets.length === 0 ? 0 : Math.max(stops.length, 1),
};
}, [horizontal]);
const update = useCallback(() => {
const m = measure();
if (!m) return;
let nearest = 0;
if (m.max > 1 && m.position >= m.max - 1) {
nearest = m.pages - 1;
} else {
let best = Number.POSITIVE_INFINITY;
m.stops.forEach((offset, i) => {
const distance = Math.abs(offset - m.position);
if (distance < best) {
best = distance;
nearest = i;
}
});
}
setPages(m.pages);
setCurrent(nearest);
setCanPrev(m.position > 1);
setCanNext(m.position < m.max - 1);
}, [measure]);
const scrollTo = useCallback(
(target: number, behavior: ScrollBehavior = "smooth") => {
const m = measure();
if (!m || m.pages === 0) return;
const i = Math.min(Math.max(target, 0), m.pages - 1);
const to = Math.min(m.stops[i] ?? 0, Math.max(m.max, 0));
const smooth = behavior === "smooth" && !prefersReducedMotion();
m.el.scrollTo({
[horizontal ? "left" : "top"]: to,
behavior: smooth ? "smooth" : "auto",
});
},
[measure, horizontal],
);
const currentRef = useRef(current);
currentRef.current = current;
const scrollNext = useCallback(() => {
const m = measure();
if (!m) return;
if (m.position < m.max - 1) scrollTo(currentRef.current + 1);
else if (loop) scrollTo(0);
}, [measure, scrollTo, loop]);
const scrollPrev = useCallback(() => {
const m = measure();
if (!m) return;
if (m.position > 1) scrollTo(currentRef.current - 1);
else if (loop) scrollTo(m.pages - 1);
}, [measure, scrollTo, loop]);
// Measure on mount and whenever the slides or the container change size.
// biome-ignore lint/correctness/useExhaustiveDependencies: runs once per orientation; the start position is only read on mount
useEffect(() => {
const el = viewportRef.current;
if (!el) return;
update();
const start = index ?? defaultIndex;
if (start > 0) scrollTo(start, "auto");
const resize = new ResizeObserver(update);
resize.observe(el);
for (const child of Array.from(el.children)) resize.observe(child);
const mutation = new MutationObserver(() => {
resize.disconnect();
resize.observe(el);
for (const child of Array.from(el.children)) resize.observe(child);
update();
});
mutation.observe(el, { childList: true });
return () => {
resize.disconnect();
mutation.disconnect();
};
}, [update, orientation]);
// A controlled `index` moves the carousel.
// biome-ignore lint/correctness/useExhaustiveDependencies: only a change of `index` (or the first measure) should scroll
useEffect(() => {
if (index === undefined || pages === 0) return;
if (index !== currentRef.current) scrollTo(index);
}, [index, pages]);
const reported = useRef<number | null>(null);
useEffect(() => {
if (pages === 0) return;
if (reported.current !== null && reported.current !== current) {
onIndexChange?.(current);
}
reported.current = current;
}, [current, pages, onIndexChange]);
// Autoplay: a tick moves on, and goes back to the start after the last one.
const isPaused = hovered || focused;
const canMove = pages > 1;
useEffect(() => {
if (!interval || isPaused || !canMove || prefersReducedMotion()) return;
const id = window.setInterval(() => {
if (document.hidden) return;
const m = measure();
if (!m) return;
if (m.position < m.max - 1) scrollTo(currentRef.current + 1);
else scrollTo(0);
}, interval);
return () => window.clearInterval(id);
}, [interval, isPaused, canMove, measure, scrollTo]);
function onKeyDown(event: KeyboardEvent<HTMLElement>) {
const target = event.target as HTMLElement;
if (target.closest("input, textarea, select, [contenteditable=true]")) {
return;
}
const back = horizontal ? "ArrowLeft" : "ArrowUp";
const forward = horizontal ? "ArrowRight" : "ArrowDown";
if (event.key === back) scrollPrev();
else if (event.key === forward) scrollNext();
else if (event.key === "Home") scrollTo(0);
else if (event.key === "End") scrollTo(pages - 1);
else return;
event.preventDefault();
}
const value = useMemo(
() => ({
orientation,
viewportRef,
current,
pages,
canPrev,
canNext,
loop,
isAutoPlaying,
scrollPrev,
scrollNext,
scrollTo: (i: number) => scrollTo(i),
update,
}),
[
orientation,
current,
pages,
canPrev,
canNext,
loop,
isAutoPlaying,
scrollPrev,
scrollNext,
scrollTo,
update,
],
);
const styles = carouselStyles({ orientation });
return (
<CarouselProvider value={value}>
<section
aria-roledescription="carousel"
aria-label={props["aria-label"]}
onKeyDown={onKeyDown}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
onFocus={() => setFocused(true)}
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) {
setFocused(false);
}
}}
style={
{
"--slides": slidesPerView,
"--gap": `${gap}px`,
} as React.CSSProperties
}
className={cn(styles.root(), className)}
>
{children}
</section>
</CarouselProvider>
);
}
export interface CarouselContentProps {
/** The `CarouselItem`s. */
children: ReactNode;
className?: string;
}
/** The row of slides. It is the part that scrolls. */
export function CarouselContent({ children, className }: CarouselContentProps) {
const { orientation, viewportRef, isAutoPlaying, update } = useCarousel();
const styles = carouselStyles({ orientation });
const slides = Children.toArray(children);
return (
<div
ref={viewportRef}
// Focusable, so the arrow keys work and a keyboard user can scroll it.
// biome-ignore lint/a11y/noNoninteractiveTabindex: a scroll container has to be focusable to be scrolled with the keyboard
tabIndex={0}
aria-live={isAutoPlaying ? "off" : "polite"}
onScroll={update}
className={cn(styles.content(), className)}
>
{slides.map((slide, i) => (
<CarouselSlideContext.Provider
// biome-ignore lint/suspicious/noArrayIndexKey: React gives each child its own key; this one only wraps it
key={i}
value={{ index: i, total: slides.length }}
>
{slide}
</CarouselSlideContext.Provider>
))}
</div>
);
}
export interface CarouselItemProps {
children?: ReactNode;
className?: string;
}
/** One slide. Put anything inside it. */
export function CarouselItem({ children, className }: CarouselItemProps) {
const { orientation } = useCarousel();
const slide = useContext(CarouselSlideContext);
const styles = carouselStyles({ orientation });
return (
// biome-ignore lint/a11y/useSemanticElements: a group named "n of N" is how the carousel pattern describes a slide
<div
role="group"
aria-roledescription="slide"
aria-label={slide ? `${slide.index + 1} of ${slide.total}` : undefined}
className={cn(styles.item(), className)}
>
{children}
</div>
);
}
export interface CarouselControlProps {
variant?: ButtonProps["variant"];
size?: ButtonProps["size"];
/** Replaces the default accessible name. */
"aria-label"?: string;
className?: string;
}
/**
* Goes to the previous slide. It sits over the start of the carousel. Move it
* with `className`, or set its position to `static` to put it in your own row.
* Disabled on the first slide unless the carousel loops.
*/
export function CarouselPrevious({
variant = "outline",
size = "sm",
className,
...props
}: CarouselControlProps) {
const { orientation, canPrev, loop, scrollPrev } = useCarousel();
const styles = carouselStyles({ orientation });
const Icon = orientation === "horizontal" ? ChevronLeftIcon : ChevronUpIcon;
return (
<Button
isIcon
variant={variant}
size={size}
aria-label={props["aria-label"] ?? "Previous slide"}
isDisabled={!canPrev && !loop}
onPress={scrollPrev}
className={cn(
styles.control(),
orientation === "horizontal"
? "top-1/2 left-2 -translate-y-1/2"
: "top-2 left-1/2 -translate-x-1/2",
"rounded-full bg-bg",
className,
)}
>
<Icon />
</Button>
);
}
/** Goes to the next slide. Disabled on the last slide unless the carousel loops. */
export function CarouselNext({
variant = "outline",
size = "sm",
className,
...props
}: CarouselControlProps) {
const { orientation, canNext, loop, scrollNext } = useCarousel();
const styles = carouselStyles({ orientation });
const Icon =
orientation === "horizontal" ? ChevronRightIcon : ChevronDownIcon;
return (
<Button
isIcon
variant={variant}
size={size}
aria-label={props["aria-label"] ?? "Next slide"}
isDisabled={!canNext && !loop}
onPress={scrollNext}
className={cn(
styles.control(),
orientation === "horizontal"
? "top-1/2 right-2 -translate-y-1/2"
: "bottom-2 left-1/2 -translate-x-1/2",
"rounded-full bg-bg",
className,
)}
>
<Icon />
</Button>
);
}
export interface CarouselDotsProps {
/** Names the dots for screen readers. Defaults to "Choose a slide". */
"aria-label"?: string;
className?: string;
}
/** One dot per place the carousel can stop, with the current one stretched. Click one to go there. */
export function CarouselDots({ className, ...props }: CarouselDotsProps) {
const { orientation, current, pages, scrollTo } = useCarousel();
const styles = carouselStyles({ orientation });
if (pages < 2) return null;
return (
// biome-ignore lint/a11y/useSemanticElements: a div with role="group" is the standard pattern for a labelled set of buttons
<div
role="group"
aria-label={props["aria-label"] ?? "Choose a slide"}
className={cn(styles.dots(), className)}
>
{Array.from({ length: pages }, (_, i) => (
<button
// biome-ignore lint/suspicious/noArrayIndexKey: the dots are a fixed count and never reorder
key={i}
type="button"
aria-label={`Go to slide ${i + 1}`}
aria-current={i === current}
onClick={() => scrollTo(i)}
className={styles.dot()}
/>
))}
</div>
);
}It imports ChevronLeftIcon, ChevronRightIcon, ChevronUpIcon and ChevronDownIcon from @/components/icons. Add those icons, or swap them for your own.
3. Use it
import {
Carousel,
CarouselContent,
CarouselDots,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel/carousel";Anatomy
A carousel, its scrolling content, the slides, and the controls around them.
<Carousel aria-label="Featured" className="w-full max-w-md">
<CarouselContent>
<CarouselItem>One</CarouselItem>
<CarouselItem>Two</CarouselItem>
<CarouselItem>Three</CarouselItem>
</CarouselContent>
<CarouselPrevious />
<CarouselNext />
<CarouselDots className="mt-4" />
</Carousel>| Part | Rendered as | Notes |
|---|---|---|
| Carousel | section (carousel) | Holds the state and the settings. Names the carousel for screen readers, and handles the arrow keys, Home and End. |
| CarouselContent | scroll container | The row of slides. It snaps, so touch, trackpad and mouse wheel work natively and always stop on a slide. |
| CarouselItem | group (slide) | One slide, named "1 of 6". Put anything inside it. |
| CarouselPrevious / CarouselNext | Button | Round icon buttons over the edges. Disabled at the ends, unless the carousel loops. |
| CarouselDots | buttons in a group | One dot per place to stop, the current one stretched. Click one to go there. |
Give the carousel a width, and for a vertical one a height too. Add an aria-label that says what is being shown.
Examples
Drag or swipe the slides, press the buttons, or focus one and use the arrow keys.
Usage
Dots
CarouselDots is its own part, so put it wherever fits: under the slides, over them, or in a toolbar.
Multiple slides
slidesPerView shows more than one slide, and gap sets the space between them. The dots stop where the last slide is fully in view.
Peek
A fractional slidesPerView leaves part of the next slide in view, a hint that there is more.
Loop
With loop the buttons never disable: Next on the last slide goes back to the first, and Previous on the first goes to the last.
Autoplay
It moves on every few seconds and returns to the start after the last slide. It pauses while the pointer is over the carousel or focus is inside it, and does not run for people who prefer reduced motion.
Vertical
The slides stack and the buttons move to the top and bottom. A vertical carousel needs a height.
Swipe only
Leave out the buttons and the dots for a plain swipeable strip. It stays keyboard-scrollable: focus it and use the arrow keys.
Controlled
Keep the slide in your own state with index and onIndexChange. It reports every change, including swipes.
slide 1 of 6
Component API
Carousel is made of the parts below.
Carousel
| Prop | Type | Default |
|---|---|---|
| orientation | "horizontal" | "vertical" | "horizontal" |
| slidesPerView | number | 1 |
| gap | number (px) | 16 |
| loop | boolean | false |
| autoPlay | boolean | number (ms) | false |
| index | number | - |
| defaultIndex | number | 0 |
| onIndexChange | (index: number) => void | - |
| aria-label | string | - |
| className | string | - |
CarouselContent, CarouselItem
| Prop | Type | Default |
|---|---|---|
| children | ReactNode | - |
| className | string | - |
CarouselPrevious, CarouselNext
| Prop | Type | Default |
|---|---|---|
| variant | Button variant | "outline" |
| size | Button size | "sm" |
| aria-label | string | "Previous slide" / "Next slide" |
| className | string | - |
CarouselDots
| Prop | Type | Default |
|---|---|---|
| aria-label | string | "Choose a slide" |
| className | string | - |