Carousel
A row of slides that scrolls a page at a time, with buttons, page dots and an optional autoplay. Built on native scroll snap, so touch, trackpads and right-to-left work as the browser does.
Carousel shows a set of slides one page at a time. Give it data: photos, which it renders as Images, or any content. It wraps Ark's carousel, which lays the slides out on native CSS scroll snap: a swipe on a touch screen, a trackpad scroll and a mouse drag all move it, and the browser snaps to the nearest page.
import { Carousel } from '@42-central/ui-react/carousel';
const slides = [
{ value: 'lake', src: '/photos/lake.jpg', alt: 'A mountain lake at dawn', width: 2400, height: 1600 },
{ value: 'falls', src: '/photos/falls.jpg', alt: 'A waterfall under a stone bridge', width: 2400, height: 1600 },
// …
];
<Carousel data={slides} ratio="16/9" loader={cdnLoader} />Playground
Component
Dir
Presets
Props
Code
<Component
ratio="16/9"
slidesPerPage={1}
loop={false}
allowMouseDrag
withControls
withIndicators
/>Full prop browser
Photos
A slide with src and alt is an Image, given the carousel's loader and a sizes of the viewport width over slidesPerPage. ratio crops every slide to the same shape, so the row never changes height from one page to the next. radius rounds every slide, xs by default; "none" squares them.
Code
<Carousel data={photos} ratio="16/9" loader={unsplash} />Several slides per page
slidesPerPage shows more than one slide at once, and a page turn moves all of them. There's one dot per page, not per slide. spacing sets the gap between slides on the kit's size scale.
Code
<Carousel data={photos} slidesPerPage={3} ratio={1} spacing="sm" loader={unsplash} />Peek
padding adds space before the first slide and after the last, and the slides snap inside it, so the neighbours peek in from both edges. It hints that there's more to scroll to.
Code
<Carousel data={photos} ratio="16/9" padding="3rem" loader={unsplash} />Autoplay
autoplay turns the page every 4 seconds, or every delay ms. It loops back to the first page by default. While it's on, a play/pause button is always in the controls, as WCAG 2.2.2 asks for anything that moves on its own.
- It pauses while the mouse is over the carousel and while keyboard focus is in it, and resumes when they leave.
- A pause pressed on the button sticks: moving the mouse away doesn't restart it. Only the button does.
- With reduced motion (
prefers-reduced-motion: reduce), autoplay is off altogether. The carousel doesn't turn on its own, the play/pause button isn't rendered (aCarousel.AutoplayTriggerin your own layout renders nothing), and the visitor can't start it. Previous, Next and the dots still work, and scroll instantly.
Code
<Carousel data={photos} ratio="16/9" autoplay={{ delay: 3000 }} loader={unsplash} />onAutoplayStatusChange(playing) fires whenever it starts or stops, whatever the reason.
Any content
A slide with content renders it as is: cards, a video, your own Image. The slide is the box: give the content h-full to fill a row of uneven heights.
Code
<Carousel
slidesPerPage={2}
radius="none"
data={steps.map(({ title, body }) => ({
value: title,
content: <Card>…</Card>,
}))}
/>Opening in a Lightbox
Inside a Lightbox, each slide becomes a button that opens the viewer at its own index, from its own pixels. Pass the same data to both. Arrow to another photo in the viewer, then close it: the carousel scrolls that photo's slide into view at once, behind the backdrop, and the image shrinks back into it. Focus lands on it too.
Code
<Lightbox data={photos} loader={unsplash}>
<Carousel data={photos} slidesPerPage={3} ratio={1} spacing="sm" loader={unsplash} />
</Lightbox>This works through the open-index seam: each slide registers a reveal alongside its element, which the viewer calls before it measures the slide. A mouse drag across the slides never opens the viewer: only a click that stays put does.
Composable parts
<Carousel> is a ready-made arrangement of parts. Build your own with Carousel.Root (state; needs slideCount), Carousel.Viewport (the scroller), one Carousel.Item per slide, and the controls you want, grouped in a Carousel.Control. Carousel.Context gives a render function the state and the commands.
Code
<Carousel.Root slideCount={photos.length} ratio="3/2" loop>
<Carousel.Viewport>
{photos.map((photo, index) => (
<Carousel.Item key={photo.value} index={index}>
<Image src={photo.src} alt={photo.alt} loader={unsplash} radius="none" className="block size-full" />
</Carousel.Item>
))}
</Carousel.Viewport>
<Carousel.Control className="justify-center">
<Carousel.PrevTrigger />
<Carousel.ProgressText />
<Carousel.NextTrigger />
</Carousel.Control>
</Carousel.Root>Custom layout
Every piece can be replaced, and the parts go anywhere inside Carousel.Root:
- Icons through
icons, a map ofprev,next,playandpause, onCarousel.Rootor the data form. A part'schildrenreplace its icon outright. The kit's own chevrons mirror on a right-to-left page; yours are drawn as given, so addrtl:-scale-x-100to an arrow. AddclassName={iconStroke}(from@42/ui-react) for the kit's 1.5px line. - Indicators through
Carousel.Indicators' child function,(page) => ReactNode. Return aCarousel.Indicatorwith your own children: it keepsaria-current, the click, the single tab stop and the arrow keys. Style the current one withdata-current:. - The progress text through
ProgressText's function child, which gets the page and the count already formatted for the locale.translations.progresschanges it everywhere instead. - Placement is plain layout: here, the page bars sit above the slides, and Previous and Next are overlaid on them.
Code
<Carousel.Root
slideCount={photos.length}
ratio="16/9"
autoplay={{ delay: 4000 }}
icons={{
prev: <ArrowLeft className={cn(iconStroke, "rtl:-scale-x-100")} />,
next: <ArrowRight className={cn(iconStroke, "rtl:-scale-x-100")} />,
play: <CirclePlay className={iconStroke} />,
pause: <CirclePause className={iconStroke} />,
}}
>
<div className="flex items-center justify-between">
<Carousel.Indicators className="gap-1.5">
{(page) => (
<Carousel.Indicator index={page} className="h-7 w-10 rounded-xs data-current:bg-brand-500 …">
{page + 1}
</Carousel.Indicator>
)}
</Carousel.Indicators>
<Carousel.ProgressText>{({ page, count }) => `Photo ${page} of ${count}`}</Carousel.ProgressText>
<Carousel.AutoplayTrigger />
</div>
<div className="relative">
<Carousel.Viewport>
{photos.map((photo, index) => (
<Carousel.Item key={photo.value} index={index}>
<Image src={photo.src} alt={photo.alt} loader={unsplash} radius="none" className="block size-full" />
</Carousel.Item>
))}
</Carousel.Viewport>
<Carousel.PrevTrigger className="absolute start-3 top-1/2 -translate-y-1/2 …" />
<Carousel.NextTrigger className="absolute end-3 top-1/2 -translate-y-1/2 …" />
</div>
</Carousel.Root>In the data form, renderItem(item, index, media) wraps or replaces a slide's media (the Image, or the item's content) while the slide and its open button stay the carousel's, and classNames reaches every element.
Right-to-left
The carousel takes its direction from the locale, through Ark. Under IntlProvider locale="ar" the first slide is on the right, a page turn scrolls to the left, the arrow buttons' icons mirror, and ← goes to the next page. Every string in this demo is translated, and numbers use the locale's digits.
Code
<IntlProvider locale="ar-EG">
<div dir="rtl" lang="ar">
<Carousel data={photos} ratio="16/9" translations={arabic} />
</div>
</IntlProvider>API
Prop
Type
Carousel.Root takes everything from ratio to onDragStatusChange, icons, translations, and a required slideCount. No part takes asChild.
CarouselItem
Prop
Type
Parts
| Part | Renders | Notes |
|---|---|---|
Carousel.Root | <div role="region"> | State, autoplay holds, and the props above. Needs slideCount. |
Carousel.Viewport | <div> | The scroller (Ark's item group). Takes the arrow keys while focus is in it. |
Carousel.Item | <div role="group"> | index, snapAlign. Cropped to the root's ratio. A button under a Lightbox; openLabel names it when the content can't, and classNames.opener styles it. |
Carousel.Control | <div> | Groups the buttons and the dots. |
Carousel.PrevTrigger, NextTrigger | <button> | 44px, round. Children replace icons.prev / icons.next. |
Carousel.AutoplayTrigger | <button> | Play or pause. Children replace icons.play / icons.pause. Renders nothing without autoplay or under reduced motion. |
Carousel.Indicators | A group of buttons | One per page. Its child function (page) => ReactNode renders each; classNames: { indicator?, dot? } restyles the default. |
Carousel.Indicator | <button> | index. Children replace the dot. aria-current and data-current on the current page. |
Carousel.ProgressText | <span> | "2 / 5". Children replace it; a function child gets { page, count }, formatted. |
Carousel.Context | Your render function | { page, count, canPrev, canNext, autoplay, playing, paused, dragging, prev, next, goto, play, pause }. The commands honour reduced motion; autoplay is false under it, and play does nothing. |
Accessibility
Following the APG carousel pattern:
- A named region. The root is a
role="region"witharia-roledescription="carousel", named bytranslations.label. Each slide is arole="group"witharia-roledescription="slide", named "3 of 8". Slides out of view arearia-hidden, and their buttons (under a Lightbox) leave the tab order. - Changes are announced. The viewport is a polite live region while autoplay isn't running, so a page turn reads the new slide. It's silent while autoplay runs.
- The buttons don't move focus. Previous and Next keep focus when pressed. At the first and last page (without
loop) they'rearia-disabled, notdisabled, so they keep focus there too. They're 44px round buttons, above the WCAG 2.5.8 minimum. The page dots are 24px targets around an 8px dot. The current one isaria-current, and it's the dots' one tab stop. - Autoplay can always be stopped (WCAG 2.2.2): its button is always there when
autoplayis on, named for what pressing it does ("Stop slide rotation"). Hovering or keyboard focus pauses it, and a pause pressed on the button sticks until play is pressed. - Reduced motion. Every control, key and Lightbox return scrolls instantly instead of smoothly. Autoplay is disabled: it never runs, its button isn't rendered, and nothing can start it, so nothing on the page moves on its own. (A server render can't know the setting, so on a reduced-motion device autoplay and its button exist for the first frame after hydration, before any page turns, then go.) Ark's own scrolling is smooth and in JavaScript, so CSS can't turn it off; the kit's controls call Ark with
instantinstead. - Keyboard:
| Key | Does |
|---|---|
| Tab | Moves to the viewport (or, under a Lightbox, the slides in view), the current page's dot (the dots are one tab stop), and the buttons. |
| → / ← | In the viewport or on a dot: next / previous page, in reading order (swapped on a right-to-left page). On a dot, focus follows. ↓ / ↑ when vertical. |
| Home / End | First / last page. |
| Enter / Space | Presses a button; opens a slide under a Lightbox. |
- Right-to-left. From the locale; see Right-to-left.
Internationalization
Every string the carousel shows or announces is in translations. Numbers arrive already formatted with Intl.NumberFormat for the locale from IntlProvider. Alt text is your content: translate it with the rest of the page.
| Key | Default |
|---|---|
label | "Carousel" |
prevLabel | "Previous slide" |
nextLabel | "Next slide" |
playLabel | "Start slide rotation" |
pauseLabel | "Stop slide rotation" |
indicatorsLabel | "Choose a slide" |
indicatorLabel | (page) => `Go to slide ${page}` |
slideLabel | (position, count) => `${position} of ${count}` |
progress | (page, count) => `${page} / ${count}` |
openLabel | (position, count) => `Open slide ${position} of ${count}` , for a photo slide with alt="" under a Lightbox |
Testing
testId lands on the region, and each item's testId on its slide. jsdom lays nothing out, so Ark sees a single page and never marks a slide in view: query slides with { hidden: true }, and stub getBoundingClientRect on the slides if a test needs several pages. Ark measures its pages a macrotask after mount, so let one pass before clicking.
render(<Carousel data={slides} onPageChange={onPageChange} />);
await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
await user.click(screen.getByRole('button', { name: 'Next slide' }));
await waitFor(() => expect(onPageChange).toHaveBeenCalledWith(1));Changelog
- #510
in-*and unnamedgroup-*selectors are scoped to the component's own attribute, so nested or wrapped components no longer pick up an ancestor's orientation, shape, invalid or hover state
- #464
No computed-style read on mount in production: the RTL direction check runs in development only
- #357
New
CarouselwithslidesPerPage,paddingpeek, mouse drag, roving indicators andautoplaythat holds on hover and focus and stops under reduced motion;icons, composable parts, and slides that open in aLightboxscrolling back to where you close
FilePreview
Shows one file in the browser's own viewers — PDF, image, video, sound, text — behind an allowlist that keeps uploaded HTML and SVG from running as your app. Plus openFile, for "open in a new tab".
Compare
A before/after slider. Two images share one box, and a handle wipes between them. Drag it, press anywhere, or use the arrow keys.