# Carousel (/docs/carousel)





`Carousel` shows a set of slides one page at a time. Give it `data`: photos, which it renders as [`Image`](/docs/image)s, 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.

```tsx
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 [#playground]

<story.Playground />

### Full prop browser [#full-prop-browser]

<story.WithControl />

## Photos [#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.

<Preview align="block" code="`<Carousel data={photos} ratio=&#x22;16/9&#x22; loader={unsplash} />`">
  <PhotosDemo ratio="16/9" />
</Preview>

## Several slides per page [#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.

<Preview align="block" code="`<Carousel data={photos} slidesPerPage={3} ratio={1} spacing=&#x22;sm&#x22; loader={unsplash} />`">
  <PhotosDemo slidesPerPage="3" ratio="1" spacing="sm" count="9" />
</Preview>

## Peek [#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.

<Preview align="block" code="`<Carousel data={photos} ratio=&#x22;16/9&#x22; padding=&#x22;3rem&#x22; loader={unsplash} />`">
  <PhotosDemo ratio="16/9" padding="3rem" />
</Preview>

## Autoplay [#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](https://www.w3.org/WAI/WCAG22/Understanding/pause-stop-hide.html) 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 (a `Carousel.AutoplayTrigger` in your own layout renders nothing), and the visitor can't start it. Previous, Next and the dots still work, and scroll instantly.

<Preview align="block" code="`<Carousel data={photos} ratio=&#x22;16/9&#x22; autoplay={{ delay: 3000 }} loader={unsplash} />`">
  <PhotosDemo ratio="16/9" autoplay="{ delay: 3000 }" />
</Preview>

`onAutoplayStatusChange(playing)` fires whenever it starts or stops, whatever the reason.

## Any content [#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.

<Preview align="block" code="&#x22;<Carousel\n  slidesPerPage={2}\n  radius=\&#x22;none\&#x22;\n  data={steps.map(({ title, body }) => ({\n    value: title,\n    content: <Card>…</Card>,\n  }))}\n/>&#x22;">
  <ContentDemo />
</Preview>

## Opening in a Lightbox [#opening-in-a-lightbox]

Inside a [`Lightbox`](/docs/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.

<Preview align="block" code="&#x22;<Lightbox data={photos} loader={unsplash}>\n  <Carousel data={photos} slidesPerPage={3} ratio={1} spacing=\&#x22;sm\&#x22; loader={unsplash} />\n</Lightbox>&#x22;">
  <LightboxDemo />
</Preview>

This works through the [open-index seam](/docs/gallery#opening-a-photo): 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 [#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.

<Preview align="block" code="&#x22;<Carousel.Root slideCount={photos.length} ratio=\&#x22;3/2\&#x22; loop>\n  <Carousel.Viewport>\n    {photos.map((photo, index) => (\n      <Carousel.Item key={photo.value} index={index}>\n        <Image src={photo.src} alt={photo.alt} loader={unsplash} radius=\&#x22;none\&#x22; className=\&#x22;block size-full\&#x22; />\n      </Carousel.Item>\n    ))}\n  </Carousel.Viewport>\n  <Carousel.Control className=\&#x22;justify-center\&#x22;>\n    <Carousel.PrevTrigger />\n    <Carousel.ProgressText />\n    <Carousel.NextTrigger />\n  </Carousel.Control>\n</Carousel.Root>&#x22;">
  <ComposedDemo />
</Preview>

## Custom layout [#custom-layout]

Every piece can be replaced, and the parts go anywhere inside `Carousel.Root`:

* **Icons** through `icons`, a map of `prev`, `next`, `play` and `pause`, on `Carousel.Root` or the data form. A part's `children` replace its icon outright. The kit's own chevrons mirror on a right-to-left page; yours are drawn as given, so add `rtl:-scale-x-100` to an arrow. Add `className={iconStroke}` (from `@42/ui-react`) for the kit's 1.5px line.
* **Indicators** through `Carousel.Indicators`' child function, `(page) => ReactNode`. Return a `Carousel.Indicator` with your own children: it keeps `aria-current`, the click, the single tab stop and the arrow keys. Style the current one with `data-current:`.
* **The progress text** through `ProgressText`'s function child, which gets the page and the count already formatted for the locale. `translations.progress` changes it everywhere instead.
* **Placement** is plain layout: here, the page bars sit above the slides, and Previous and Next are overlaid on them.

<Preview align="block" code="&#x22;<Carousel.Root\n  slideCount={photos.length}\n  ratio=\&#x22;16/9\&#x22;\n  autoplay={{ delay: 4000 }}\n  icons={{\n    prev: <ArrowLeft className={cn(iconStroke, \&#x22;rtl:-scale-x-100\&#x22;)} />,\n    next: <ArrowRight className={cn(iconStroke, \&#x22;rtl:-scale-x-100\&#x22;)} />,\n    play: <CirclePlay className={iconStroke} />,\n    pause: <CirclePause className={iconStroke} />,\n  }}\n>\n  <div className=\&#x22;flex items-center justify-between\&#x22;>\n    <Carousel.Indicators className=\&#x22;gap-1.5\&#x22;>\n      {(page) => (\n        <Carousel.Indicator index={page} className=\&#x22;h-7 w-10 rounded-xs data-current:bg-brand-500 …\&#x22;>\n          {page + 1}\n        </Carousel.Indicator>\n      )}\n    </Carousel.Indicators>\n    <Carousel.ProgressText>{({ page, count }) => `Photo ${page} of ${count}`}</Carousel.ProgressText>\n    <Carousel.AutoplayTrigger />\n  </div>\n  <div className=\&#x22;relative\&#x22;>\n    <Carousel.Viewport>\n      {photos.map((photo, index) => (\n        <Carousel.Item key={photo.value} index={index}>\n          <Image src={photo.src} alt={photo.alt} loader={unsplash} radius=\&#x22;none\&#x22; className=\&#x22;block size-full\&#x22; />\n        </Carousel.Item>\n      ))}\n    </Carousel.Viewport>\n    <Carousel.PrevTrigger className=\&#x22;absolute start-3 top-1/2 -translate-y-1/2 …\&#x22; />\n    <Carousel.NextTrigger className=\&#x22;absolute end-3 top-1/2 -translate-y-1/2 …\&#x22; />\n  </div>\n</Carousel.Root>&#x22;">
  <CustomLayoutDemo />
</Preview>

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 [#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 <kbd>←</kbd> goes to the next page. Every string in this demo is translated, and numbers use the locale's digits.

<Preview align="block" code="&#x22;<IntlProvider locale=\&#x22;ar-EG\&#x22;>\n  <div dir=\&#x22;rtl\&#x22; lang=\&#x22;ar\&#x22;>\n    <Carousel data={photos} ratio=\&#x22;16/9\&#x22; translations={arabic} />\n  </div>\n</IntlProvider>&#x22;">
  <DirectionDemo />
</Preview>

## API [#api]

<TypeTable
  type="{
  data: {
    type: &#x22;CarouselItem[]&#x22;,
    required: true,
    description: &#x22;The slides, in order: photos (src and alt) or any content.&#x22;,
  },
  ratio: {
    type: &#x22;number | `${number}/${number}`&#x22;,
    description: &#x22;The aspect ratio of every slide.&#x22;,
  },
  radius: {
    type: &#x22;'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'full'&#x22;,
    default: &#x22;'xs'&#x22;,
    description: &#x22;Corner radius of every slide, on Image's scale.&#x22;,
  },
  spacing: {
    type: &#x22;'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl'&#x22;,
    default: &#x22;'md'&#x22;,
    description: &#x22;The gap between slides: 0, 4, 6, 8, 12 or 16px.&#x22;,
  },
  slidesPerPage: {
    type: &#x22;number&#x22;,
    default: &#x22;1&#x22;,
    description: &#x22;Slides visible at once.&#x22;,
  },
  slidesPerMove: {
    type: &#x22;number | 'auto'&#x22;,
    default: &#x22;'auto'&#x22;,
    description: &#x22;Slides moved per page turn. auto moves a whole page.&#x22;,
  },
  padding: {
    type: &#x22;string&#x22;,
    description: &#x22;Space before the first slide and after the last, so the neighbours peek in.&#x22;,
  },
  &#x22;page / defaultPage / onPageChange&#x22;: {
    type: &#x22;number / number / (page: number) => void&#x22;,
    default: &#x22;0&#x22;,
    description: &#x22;The current page, 0-based.&#x22;,
  },
  loop: {
    type: &#x22;boolean&#x22;,
    default: &#x22;true with autoplay, else false&#x22;,
    description: &#x22;Go from the last page to the first, and back.&#x22;,
  },
  orientation: {
    type: &#x22;'horizontal' | 'vertical'&#x22;,
    default: &#x22;'horizontal'&#x22;,
    description: &#x22;Vertical needs a height on the viewport (classNames.viewport).&#x22;,
  },
  autoplay: {
    type: &#x22;boolean | { delay: number }&#x22;,
    default: &#x22;false&#x22;,
    description: &#x22;Turn the page every 4s, or every delay ms. Adds the play/pause button. Off, with no button, under prefers-reduced-motion.&#x22;,
  },
  onAutoplayStatusChange: {
    type: &#x22;(playing: boolean) => void&#x22;,
    description: &#x22;Autoplay started or stopped.&#x22;,
  },
  allowMouseDrag: {
    type: &#x22;boolean&#x22;,
    default: &#x22;true&#x22;,
    description: &#x22;Drag the slides with a mouse. Touch and trackpads always scroll.&#x22;,
  },
  onDragStatusChange: {
    type: &#x22;(dragging: boolean) => void&#x22;,
    description: &#x22;A mouse drag started or ended.&#x22;,
  },
  withControls: { type: &#x22;boolean&#x22;, default: &#x22;true&#x22;, description: &#x22;The previous and next buttons.&#x22; },
  withIndicators: { type: &#x22;boolean&#x22;, default: &#x22;true&#x22;, description: &#x22;One dot per page.&#x22; },
  loader: {
    type: &#x22;ImageLoader&#x22;,
    description: &#x22;Forwarded to every photo slide's Image, for a srcset from your CDN.&#x22;,
  },
  sizes: {
    type: &#x22;string&#x22;,
    description: &#x22;The sizes of every photo slide. The viewport width over slidesPerPage by default.&#x22;,
  },
  icons: {
    type: &#x22;{ prev?, next?, play?, pause? }&#x22;,
    description: &#x22;Replaces the default icons; a missing key keeps its default. A part's children win over these.&#x22;,
  },
  renderItem: {
    type: &#x22;(item, index, media) => ReactNode&#x22;,
    description: &#x22;Replaces a slide's media; media is the Image or the item's content. The slide and its open button stay.&#x22;,
  },
  translations: { type: &#x22;CarouselTranslations&#x22;, description: &#x22;See Internationalization.&#x22; },
  classNames: {
    type: &#x22;{ root?, viewport?, item?, opener?, image?, control?, trigger?, prev?, next?, autoplay?, indicators?, indicator?, dot? }&#x22;,
    description: &#x22;Per-part classes. trigger applies to the previous, next and autoplay buttons alike; opener is a slide's button under a Lightbox; dot is the default indicator's mark.&#x22;,
  },
  testId: {
    type: &#x22;string&#x22;,
    description: &#x22;Renders as data-testid on the root. See [Testing](/docs/testing).&#x22;,
  },
}"
/>

`Carousel.Root` takes everything from `ratio` to `onDragStatusChange`, `icons`, `translations`, and a required `slideCount`. No part takes `asChild`.

### CarouselItem [#carouselitem]

<TypeTable
  type="{
  value: { type: &#x22;string&#x22;, required: true, description: &#x22;A stable key for the slide.&#x22; },
  &#x22;src + alt&#x22;: {
    type: &#x22;string&#x22;,
    description: &#x22;A photo slide. alt is required with src: \&#x22;\&#x22; for a decorative photo.&#x22;,
  },
  &#x22;width, height, placeholder, quality, fallback, fit, position&#x22;: {
    type: &#x22;…&#x22;,
    description: &#x22;Passed to the photo's Image.&#x22;,
  },
  content: {
    type: &#x22;ReactNode&#x22;,
    description: &#x22;Anything else, instead of src. The slide is its box.&#x22;,
  },
  testId: { type: &#x22;string&#x22;, description: &#x22;Renders as data-testid on the slide.&#x22; },
}"
/>

### Parts [#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 [#accessibility]

Following the [APG carousel pattern](https://www.w3.org/WAI/ARIA/apg/patterns/carousel/):

* **A named region.** The root is a `role="region"` with `aria-roledescription="carousel"`, named by `translations.label`. Each slide is a `role="group"` with `aria-roledescription="slide"`, named "3 of 8". Slides out of view are `aria-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're `aria-disabled`, not `disabled`, so they keep focus there too. They're 44px round buttons, above the [WCAG 2.5.8](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html) minimum. The page dots are 24px targets around an 8px dot. The current one is `aria-current`, and it's the dots' one tab stop.
* **Autoplay can always be stopped** (WCAG 2.2.2): its button is always there when `autoplay` is 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 `instant` instead.
* **Keyboard:**

| Key                                 | Does                                                                                                                                                                       |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <kbd>Tab</kbd>                      | 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.                                     |
| <kbd>→</kbd> / <kbd>←</kbd>         | 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. <kbd>↓</kbd> / <kbd>↑</kbd> when vertical. |
| <kbd>Home</kbd> / <kbd>End</kbd>    | First / last page.                                                                                                                                                         |
| <kbd>Enter</kbd> / <kbd>Space</kbd> | Presses a button; opens a slide under a Lightbox.                                                                                                                          |

* **Right-to-left.** From the locale; see [Right-to-left](#right-to-left).

## Internationalization [#internationalization]

Every string the carousel shows or announces is in `translations`. Numbers arrive already formatted with `Intl.NumberFormat` for the locale from [`IntlProvider`](/docs/intl). 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 [#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.

```tsx
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));
```
