Skip to content

Carousel

Shows a set of similar items in a row or a column that people move through with buttons, keys or a swipe.

Bergamo52 people, 3 lines
Brescia41 people, 2 lines
Padova38 people, 2 lines
Bologna24 people, 1 lines

Installation

pnpm dlx shadcn@latest add @silkware/carousel

To copy the component by hand, install its dependencies and the Button:

pnpm add embla-carousel-react lucide-react cn

Then copy the source into components/ui/carousel.tsx:

components/ui/carousel.tsx
"use client"
import * as React from "react"import { cn } from "cn"import useEmblaCarousel, {  type UseEmblaCarouselType,} from "@animate-ui/react/primitives/carousel"
import { Button } from "@/components/ui/button"import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"
type CarouselApi = UseEmblaCarouselType[1]type UseCarouselParameters = Parameters<typeof useEmblaCarousel>type CarouselOptions = UseCarouselParameters[0]type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {  opts?: CarouselOptions  plugins?: CarouselPlugin  orientation?: "horizontal" | "vertical"  setApi?: (api: CarouselApi) => void}
type CarouselContextProps = {  carouselRef: ReturnType<typeof useEmblaCarousel>[0]  api: ReturnType<typeof useEmblaCarousel>[1]  scrollPrev: () => void  scrollNext: () => void  canScrollPrev: boolean  canScrollNext: boolean} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {  const context = React.useContext(CarouselContext)
  if (!context) {    throw new Error("useCarousel must be used within a <Carousel />")  }
  return context}
function Carousel({  orientation = "horizontal",  opts,  setApi,  plugins,  className,  children,  ...props}: React.ComponentProps<"div"> & CarouselProps) {  const [carouselRef, api] = useEmblaCarousel(    {      ...opts,      axis: orientation === "horizontal" ? "x" : "y",    },    plugins  )  const [canScrollPrev, setCanScrollPrev] = React.useState(false)  const [canScrollNext, setCanScrollNext] = React.useState(false)
  const onSelect = React.useCallback((api: CarouselApi) => {    if (!api) return    setCanScrollPrev(api.canScrollPrev())    setCanScrollNext(api.canScrollNext())  }, [])
  const scrollPrev = React.useCallback(() => {    api?.scrollPrev()  }, [api])
  const scrollNext = React.useCallback(() => {    api?.scrollNext()  }, [api])
  const handleKeyDown = React.useCallback(    (event: React.KeyboardEvent<HTMLDivElement>) => {      if (event.key === "ArrowLeft") {        event.preventDefault()        scrollPrev()      } else if (event.key === "ArrowRight") {        event.preventDefault()        scrollNext()      }    },    [scrollPrev, scrollNext]  )
  React.useEffect(() => {    if (!api || !setApi) return    setApi(api)  }, [api, setApi])
  React.useEffect(() => {    if (!api) return    onSelect(api)    api.on("reInit", onSelect)    api.on("select", onSelect)
    return () => {      api?.off("select", onSelect)    }  }, [api, onSelect])
  return (    <CarouselContext.Provider      value={{        carouselRef,        api: api,        opts,        orientation:          orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),        scrollPrev,        scrollNext,        canScrollPrev,        canScrollNext,      }}    >      <div        onKeyDownCapture={handleKeyDown}        className={cn("relative", className)}        role="region"        aria-roledescription="carousel"        data-slot="carousel"        {...props}      >        {children}      </div>    </CarouselContext.Provider>  )}
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {  const { carouselRef, orientation } = useCarousel()
  return (    <div      ref={carouselRef}      className="overflow-hidden"      data-slot="carousel-content"    >      <div        className={cn(          "flex",          orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",          className        )}        {...props}      />    </div>  )}
function CarouselItem({ className, ...props }: React.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",        orientation === "horizontal" ? "pl-4" : "pt-4",        className      )}      {...props}    />  )}
function CarouselPrevious({  className,  variant = "outline",  size = "icon-sm",  ...props}: React.ComponentProps<typeof Button>) {  const { orientation, scrollPrev, canScrollPrev } = useCarousel()
  return (    <Button      data-slot="carousel-previous"      variant={variant}      size={size}      className={cn(        "absolute touch-manipulation rounded-full",        orientation === "horizontal"          ? "inset-y-0 -left-12 my-auto"          : "-top-12 left-1/2 -translate-x-1/2 rotate-90",        className      )}      isDisabled={!canScrollPrev}      onPress={scrollPrev}      {...props}    >      <ChevronLeftIcon />      <span className="sr-only">Previous slide</span>    </Button>  )}
function CarouselNext({  className,  variant = "outline",  size = "icon-sm",  ...props}: React.ComponentProps<typeof Button>) {  const { orientation, scrollNext, canScrollNext } = useCarousel()
  return (    <Button      data-slot="carousel-next"      variant={variant}      size={size}      className={cn(        "absolute touch-manipulation rounded-full",        orientation === "horizontal"          ? "inset-y-0 -right-12 my-auto"          : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",        className      )}      isDisabled={!canScrollNext}      onPress={scrollNext}      {...props}    >      <ChevronRightIcon />      <span className="sr-only">Next slide</span>    </Button>  )}
export {  type CarouselApi,  Carousel,  CarouselContent,  CarouselItem,  CarouselPrevious,  CarouselNext,  useCarousel,}

Usage

import {  Carousel,  CarouselContent,  CarouselItem,  CarouselNext,  CarouselPrevious,} from "@/components/ui/carousel"
<Carousel aria-label="Brevia sites">  <CarouselContent>    <CarouselItem aria-label="1 of 3">Bergamo</CarouselItem>    <CarouselItem aria-label="2 of 3">Brescia</CarouselItem>    <CarouselItem aria-label="3 of 3">Padova</CarouselItem>  </CarouselContent>  <CarouselPrevious />  <CarouselNext /></Carousel>

The carousel is built on Embla Carousel. Embla provides the dragging, the snapping and the scroll logic, and this component adds the structure, the buttons and the keyboard handling.

Three things people get wrong:

  • The previous and next buttons sit 48px outside the carousel (-left-12 and -right-12), so the carousel needs room on both sides. Wrap it in a container with px-12, as the examples do, or the buttons overflow and may be clipped.
  • Each item is the full width by default. Set a basis-* class on CarouselItem for several items per view.
  • The opts prop goes to Embla as options. Embla compares the options by value, so an inline object does not reset the carousel; changing a value does.

Examples

Sizes

Set the width of items with a basis class on CarouselItem. basis-1/2 shows two, and basis-2/3 shows one and a peek of the next. Use opts={{ align: "start" }} so the first item sits at the start.

Line 1
Line 2
Line 3
Line 4
Line 5

Spacing

The gap is the left padding of each item, balanced by a negative margin on the content. Change both together: -ml-1 on CarouselContent and pl-1 on each CarouselItem.

Line 1
Line 2
Line 3
Line 4
Line 5

Orientation

orientation="vertical" stacks the items in a column. Give CarouselContent a height, and leave room above and below for the buttons.

Steel bar arrives Thursday.
Bearings held for inspection.
Gasket kits delivered to Padova.
Stock count scheduled for Friday.

Loop

opts={{ loop: true }} goes from the last item to the first. The buttons stay enabled all the way round.

Morning
Afternoon
Night

API

setApi hands you the Embla API, which lets you read the position and react to changes. Use it to show "Site 2 of 4" in text, so the position does not depend on the picture.

Bergamo
Brescia
Padova
Bologna

Site 0 of 0

Accessibility

KeyAction
ArrowRightScrolls to the next item, when focus is inside the carousel.
ArrowLeftScrolls to the previous item, when focus is inside the carousel.
TabMoves focus between the buttons and any controls inside the items.
EnterPresses the focused previous or next button.
SpacePresses the focused previous or next button.

The component provides:

  • A region with aria-roledescription="carousel", and items that are groups with aria-roledescription="slide".
  • Previous and next buttons with the labels "Previous slide" and "Next slide", disabled at the ends unless the carousel loops.
  • Left and right arrow handling on the carousel. A vertical carousel uses the same two keys: up and down are not bound.

You provide:

  • An aria-label on the Carousel that names the set, and on each CarouselItem that gives its position, such as "2 of 4".
  • The position in text, for example with the API example above.
  • A way to reach every item without the carousel: content that people must see should not be hidden in a slide.
  • No automatic advance. Moving content on its own fails people who read slowly.

Guidelines

When to use

  • To browse a set of similar items where the next one is a guess, such as catalogue items or sites.
  • To save space on a small screen for a row of cards that people skim.

When not to use

  • For content people must see or act on. Hidden slides are not read. Show the content in a Table, a list of Items, or a Tabs set.
  • For steps of a task. Use a numbered list or a stepper, with each step visible in the outline.
  • For a few items that fit. Show them in a row or a grid.
  • For a long list people search. Use a Table.

Content

  • Items share a shape: the same fields, the same height.
  • Keep the set short, under ten items, and name it with an aria-label.
  • Show a peek of the next item to tell people there is more.
  • Put the position in text when it matters: "Site 2 of 4".

Hidden actions

Steel bar 40 mm
Bearing 6204-2RS
Gasket kit GK-12
Housing H-88
Do

Use a carousel to browse similar items, with a peek of the next.

Review order PO-2417
Don’t

Don’t hide the action on a slide the person might never reach.

API reference

Renders a div with role="region" that provides the Embla instance to its children. It accepts every div prop and the props below.

PropTypeDefaultDescription
orientation?"horizontal" | "vertical""horizontal"The scroll axis.
opts?EmblaOptionsTypeNoneOptions passed to Embla, such as align, loop and dragFree. The axis is set by orientation.
plugins?EmblaPluginType[]NoneEmbla plugins. None are installed by default.
setApi?(api: CarouselApi) => voidNoneCalled with the Embla API once it is ready.
className?stringNoneClasses merged after the base classes.

CarouselContent

Renders the Embla viewport with overflow-hidden and, inside it, a flex container that holds the items. Its className and other props apply to the flex container.

CarouselItem

Renders a div with role="group" and aria-roledescription="slide". Each item is the full width of the viewport; set a basis class to change that. It accepts every div prop.

CarouselPrevious and CarouselNext

Render a round outline Button with a chevron and visually hidden text. They are disabled when there is nowhere to go. They accept every Button prop.

PropTypeDefaultDescription
variant?ButtonProps variant"outline"The button variant.
size?ButtonProps size"icon-sm"The button size.

CarouselApi

The type of the Embla API, handed to setApi. Use selectedScrollSnap(), scrollSnapList(), scrollTo(index) and on("select", handler). See the Embla API docs.

useCarousel

A hook for components inside a Carousel. It returns api, scrollPrev, scrollNext, canScrollPrev, canScrollNext, orientation and opts. It throws when used outside a carousel.