@cf/ui

@cf/carousel

Carousel

A horizontally or vertically scrolling set of slides on Embla, with previous and next buttons and arrow-key support.

The counter reads from setApi. Click a slide and the arrow keys move it too.

Slide 1 of 5

Sketch
Prototype
Critique
Ship
Revisit

shadcn's carousel over embla-carousel-react, with Phosphor arrows. The buttons disable at each end, and Left and Right arrow keys move between slides from anywhere inside the root.

It's the case-study carousel in MDX, with the buttons and a Slide n of m counter in a row above the track. A few upstream rough edges are still in it: arrow keys are Left and Right even when orientation="vertical", the reInit listener is never removed, and it still uses forwardRef.

import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";
 
<Carousel className="mx-auto max-w-6xl" setApi={setApi}>
  <div className="flex items-center justify-center gap-3">
    <CarouselPrevious />
    <p>Slide {current} of {count}</p>
    <CarouselNext />
  </div>
  <CarouselContent>
    {slides.map((slide) => (
      <CarouselItem key={slide.id}>{slide.node}</CarouselItem>
    ))}
  </CarouselContent>
</Carousel>

Props

PropTypeDefault
orientationhorizontal | verticalhorizontal
optsEmbla optionsโ€”
pluginsEmbla pluginsโ€”
setApi(api: CarouselApi) => voidโ€”

Rules

The same rules ship in DESIGN.md and the MCP server, for the agents building with this.

  • must

    Wrap every slide in CarouselItem inside CarouselContent, and keep CarouselPrevious and CarouselNext inside the Carousel root, which provides their context.

    items-inside-content

  • must

    Place CarouselPrevious and CarouselNext yourself, because they have no positioning classes of their own.

    position-the-buttons

  • should

    Put a max width on Carousel, not on CarouselContent.

    The overflow-hidden wrapper around the track is what clips, so constraining only the track lets the neighbouring slide spill into view.

    constrain-the-root

  • should

    Show where the person is (for example Slide 2 of 5) using the setApi callback, since the component has no dots or counter of its own.

    show-position

Install

bunx shadcn@latest add @cf/carousel

Needs the @cf registry in your components.json once. The theme and any sibling components come along automatically.

Source

carousel.tsxShow
"use client";
 
import { ArrowLeftIcon, ArrowRightIcon } from "@phosphor-icons/react";
import { cn } from "cn";
import useEmblaCarousel, {
  type UseEmblaCarouselType,
} from "embla-carousel-react";
import * as React from "react";
import { Button } from "./button";
 
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;
}
 
const Carousel = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
  (
    {
      orientation = "horizontal",
      opts,
      setApi,
      plugins,
      className,
      children,
      ...props
    },
    ref
  ) => {
    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={{
          api,
          canScrollNext,
          canScrollPrev,
          carouselRef,
          opts,
          orientation:
            orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
          scrollNext,
          scrollPrev,
        }}
      >
        <div
          aria-roledescription="carousel"
          className={cn("relative", className)}
          onKeyDownCapture={handleKeyDown}
          ref={ref}
          role="region"
          {...props}
        >
          {children}
        </div>
      </CarouselContext.Provider>
    );
  }
);
Carousel.displayName = "Carousel";
 
const CarouselContent = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
  const { carouselRef, orientation } = useCarousel();
 
  return (
    <div className="overflow-hidden" ref={carouselRef}>
      <div
        className={cn(
          "flex",
          orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
          className
        )}
        ref={ref}
        {...props}
      />
    </div>
  );
});
CarouselContent.displayName = "CarouselContent";
 
const CarouselItem = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
  const { orientation } = useCarousel();
 
  return (
    <div
      aria-roledescription="slide"
      className={cn(
        "min-w-0 shrink-0 grow-0 basis-full",
        orientation === "horizontal" ? "pl-4" : "pt-4",
        className
      )}
      ref={ref}
      role="group"
      {...props}
    />
  );
});
CarouselItem.displayName = "CarouselItem";
 
const CarouselPrevious = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
  const { orientation, scrollPrev, canScrollPrev } = useCarousel();
 
  return (
    <Button
      className={cn("h-8 w-8 rounded-full", className)}
      disabled={!canScrollPrev}
      onClick={scrollPrev}
      ref={ref}
      size={size}
      variant={variant}
      {...props}
    >
      <ArrowLeftIcon data-icon="inline-start" />
      <span className="sr-only">Previous slide</span>
    </Button>
  );
});
CarouselPrevious.displayName = "CarouselPrevious";
 
const CarouselNext = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
  const { orientation, scrollNext, canScrollNext } = useCarousel();
 
  return (
    <Button
      className={cn("h-8 w-8 rounded-full", className)}
      disabled={!canScrollNext}
      onClick={scrollNext}
      ref={ref}
      size={size}
      variant={variant}
      {...props}
    >
      <ArrowRightIcon data-icon="inline-start" />
      <span className="sr-only">Next slide</span>
    </Button>
  );
});
CarouselNext.displayName = "CarouselNext";
 
export {
  Carousel,
  type CarouselApi,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
};