Menu

Components

Drawer

A panel that slides in from the edge of the screen, for menus, filters, details and forms that should not take over the page.

Introduction

Drawer is a panel on the edge of the screen. It opens over the page without leaving it, so the user keeps their place: a menu on the left, the details of a row on the right, a filter panel, a cart, a sheet of actions at the bottom of a phone.

  • It behaves like a dialog: the page behind is dimmed and cannot be used or scrolled, Tab stays inside the panel, Escape closes it, and focus returns to the button that opened it.
  • It slides in from any of the four edges, in five sizes. A side drawer has a width, and a top or bottom one is as tall as its content, up to a limit. It is skipped for people who prefer reduced motion.
  • Four looks with variant: default, floating (detached from the edges), sticky (no backdrop, the page stays usable) and nested (a drawer inside a drawer).
  • The header and footer stay in view while the body scrolls, and the title names the drawer for screen readers.
  • Uncontrolled: it opens when its button is pressed. Or control it with isOpen.

For a short message or a decision that needs the whole screen's attention, use Dialog. For something small next to its button, use Popover.

Installation

centerUI has no CLI or registry yet: components are copied into your project. Drawer uses Button for its close 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 clsx

Add 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/drawer-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for Drawer. `dialog-overlay` gives the backdrop its fade (see
// globals.css, it is the same as a Dialog's), and `drawer-modal` slides the
// panel in from the edge it sits on: the panel sets `--drawer-offset` to where
// it comes from.
//
// The variants:
// - default: a panel flush with an edge.
// - floating: detached from the edges, rounded all around.
// - sticky: no backdrop and no lock: the page behind stays usable.
// - nested: a drawer opened from another drawer, stacked on it.
export const drawerStyles = tv({
  slots: {
    overlay: "dialog-overlay fixed inset-0 z-50 flex bg-black/50",
    panel:
      "drawer-modal relative flex flex-col bg-card text-card-fg shadow-xl outline-none",
    dialog: "flex min-h-0 flex-1 flex-col outline-none",
    header: "flex flex-col gap-1.5 px-6 pt-6 pr-12 pb-4",
    title: "m-0 text-lg leading-snug font-semibold",
    description: "m-0 text-sm text-muted-fg",
    body: "min-h-0 flex-1 overflow-y-auto px-6 py-2 text-sm",
    footer:
      "flex flex-col-reverse gap-2 px-6 pt-4 pb-6 sm:flex-row sm:justify-end",
    close: "absolute top-3 right-3",
  },
  variants: {
    placement: {
      right: {
        overlay: "justify-end",
        panel: "h-full w-full border-l [--drawer-offset:translateX(100%)]",
      },
      left: {
        overlay: "justify-start",
        panel: "h-full w-full border-r [--drawer-offset:translateX(-100%)]",
      },
      top: {
        overlay: "items-start",
        panel:
          "w-full rounded-b-2xl border-b [--drawer-offset:translateY(-100%)]",
      },
      bottom: {
        overlay: "items-end",
        panel:
          "w-full rounded-t-2xl border-t [--drawer-offset:translateY(100%)]",
      },
    },
    // How wide a side drawer is, or how tall a top or bottom one can grow.
    size: {
      sm: {},
      md: {},
      lg: {},
      xl: {},
      full: {},
    },
    variant: {
      default: {},
      floating: { overlay: "p-4", panel: "rounded-2xl border" },
      sticky: { panel: "fixed z-40 shadow-lg" },
      nested: { overlay: "bg-black/25", panel: "shadow-2xl" },
    },
    // A drawer opened from this one is on top of it, so this one steps back.
    hasChild: {
      true: {
        panel:
          "transition-[scale,translate] duration-300 ease-out scale-[0.96]",
      },
      false: {
        panel: "transition-[scale,translate] duration-300 ease-out",
      },
    },
  },
  compoundVariants: [
    ...(["right", "left"] as const).flatMap((placement) => [
      { placement, size: "sm" as const, class: { panel: "max-w-xs" } },
      { placement, size: "md" as const, class: { panel: "max-w-sm" } },
      { placement, size: "lg" as const, class: { panel: "max-w-lg" } },
      { placement, size: "xl" as const, class: { panel: "max-w-2xl" } },
      { placement, size: "full" as const, class: { panel: "max-w-none" } },
    ]),
    ...(["top", "bottom"] as const).flatMap((placement) => [
      { placement, size: "sm" as const, class: { panel: "max-h-[35dvh]" } },
      { placement, size: "md" as const, class: { panel: "max-h-[55dvh]" } },
      { placement, size: "lg" as const, class: { panel: "max-h-[80dvh]" } },
      { placement, size: "xl" as const, class: { panel: "max-h-[95dvh]" } },
      {
        placement,
        size: "full" as const,
        class: { panel: "h-dvh max-h-none rounded-none" },
      },
    ]),
    // Floating: the panel is a box, so it comes from further away.
    {
      variant: "floating",
      placement: "right",
      class: { panel: "[--drawer-offset:translateX(calc(100%+1rem))]" },
    },
    {
      variant: "floating",
      placement: "left",
      class: { panel: "[--drawer-offset:translateX(calc(-100%-1rem))]" },
    },
    {
      variant: "floating",
      placement: "top",
      class: { panel: "[--drawer-offset:translateY(calc(-100%-1rem))]" },
    },
    {
      variant: "floating",
      placement: "bottom",
      class: { panel: "[--drawer-offset:translateY(calc(100%+1rem))]" },
    },
    // Full height on top and bottom keeps the gap around it.
    {
      variant: "floating",
      placement: ["top", "bottom"],
      size: "full",
      class: { panel: "h-[calc(100dvh-2rem)] rounded-2xl" },
    },
    // Sticky: where the panel is fixed on the screen.
    {
      variant: "sticky",
      placement: "right",
      class: { panel: "inset-y-0 right-0" },
    },
    {
      variant: "sticky",
      placement: "left",
      class: { panel: "inset-y-0 left-0" },
    },
    {
      variant: "sticky",
      placement: "top",
      class: { panel: "inset-x-0 top-0" },
    },
    {
      variant: "sticky",
      placement: "bottom",
      class: { panel: "inset-x-0 bottom-0" },
    },
    // Nested: narrower than the drawer under it, so its edge shows.
    {
      variant: "nested",
      placement: ["right", "left"],
      class: { panel: "w-[calc(100%-2rem)]" },
    },
    {
      variant: "nested",
      placement: "right",
      class: { panel: "rounded-l-2xl" },
    },
    { variant: "nested", placement: "left", class: { panel: "rounded-r-2xl" } },
    {
      variant: "nested",
      placement: ["top", "bottom"],
      class: { panel: "max-h-[calc(100dvh-2rem)]" },
    },
    // The drawer under a nested one moves away a little.
    { hasChild: true, placement: "right", class: { panel: "-translate-x-4" } },
    { hasChild: true, placement: "left", class: { panel: "translate-x-4" } },
    { hasChild: true, placement: "top", class: { panel: "translate-y-4" } },
    { hasChild: true, placement: "bottom", class: { panel: "-translate-y-4" } },
  ],
  defaultVariants: {
    placement: "right",
    size: "md",
    variant: "default",
    hasChild: false,
  },
});
src/types/drawer-context.tsShow code
import { createContext, useContext } from "react";

export type DrawerVariant = "default" | "floating" | "sticky" | "nested";

/** What a DrawerContent tells its parts, and any drawer opened inside it. */
export interface DrawerContextValue {
  variant: DrawerVariant;
  /** Called by a drawer opened inside this one, while it is open. */
  setChildOpen: (isOpen: boolean) => void;
}

const DrawerContext = createContext<DrawerContextValue | null>(null);

export const DrawerProvider = DrawerContext.Provider;

/** The nearest DrawerContent, or null outside of one. */
export function useDrawerContext() {
  return useContext(DrawerContext);
}

2. Add the Drawer file

src/components/ui/drawer/drawer.tsxShow code
"use client";

import {
  type ReactNode,
  useContext,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import {
  Dialog as AriaDialog,
  DialogTrigger,
  type DialogTriggerProps,
  Heading,
  Modal,
  ModalOverlay,
  OverlayTriggerStateContext,
} from "react-aria-components";
import { createPortal } from "react-dom";
import { XIcon } from "@/components/icons";
import { Button, type ButtonProps } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import {
  type DrawerContextValue,
  DrawerProvider,
  type DrawerVariant,
  useDrawerContext,
} from "@/types/drawer-context";
import { drawerStyles } from "@/types/drawer-styles";

export type DrawerProps = DialogTriggerProps;

/**
 * A panel that slides in from the edge of the screen: a menu, a filter panel,
 * a cart, the details of a row, a form that should not lose the page behind
 * it. It behaves like a dialog (the page behind is dimmed and cannot be used,
 * focus stays inside, Escape closes it) but keeps the page in view, and on a
 * phone the bottom edge makes a sheet. It is a wrapper with no look of its
 * own: put the button that opens it and a `DrawerContent` inside.
 *
 * It is uncontrolled: it opens when the trigger is pressed. Open it from
 * elsewhere with `isOpen` and `onOpenChange`, or start open with `defaultOpen`.
 *
 * @example
 * <Drawer>
 *   <Button>Filters</Button>
 *   <DrawerContent placement="right">
 *     <DrawerHeader><DrawerTitle>Filters</DrawerTitle></DrawerHeader>
 *     <DrawerBody>...</DrawerBody>
 *   </DrawerContent>
 * </Drawer>
 */
export function Drawer(props: DrawerProps) {
  return <DialogTrigger {...props} />;
}

export interface DrawerContentProps {
  /** The content, or a function that receives `close`. */
  children: ReactNode | ((options: { close: () => void }) => ReactNode);
  /**
   * The look of the drawer:
   * - `default`: a panel flush with an edge.
   * - `floating`: further from the edges, with a border and a bigger shadow
   *   on the card color.
   * - `sticky`: no backdrop and no lock, so the page behind stays usable. It
   *   stays until it is closed.
   * - `nested`: for a drawer opened from inside another drawer. It lies on
   *   top of it with a lighter backdrop, and the drawer under it steps back.
   */
  variant?: DrawerVariant;
  /** The edge it slides in from. */
  placement?: "right" | "left" | "top" | "bottom";
  /**
   * How wide a side drawer is, or how tall a top or bottom one can grow. A top
   * or bottom drawer is as tall as its content, up to this. `full` fills the
   * screen.
   */
  size?: "sm" | "md" | "lg" | "xl" | "full";
  /** Close when the user clicks outside. Defaults to `true`. Not used by `sticky`, which has no outside. */
  isDismissable?: boolean;
  /** Do not close on Escape. */
  isKeyboardDismissDisabled?: boolean;
  /** The X button in the corner. Defaults to `true`. */
  showCloseButton?: boolean;
  /** Names the drawer when it has no `DrawerTitle`. */
  "aria-label"?: string;
  /** Classes for the panel. */
  className?: string;
}

// A drawer opened inside another one tells it, for as long as it is open, so
// the one under can step back.
function RegisterWithParent({ parent }: { parent: DrawerContextValue }) {
  useEffect(() => {
    parent.setChildOpen(true);
    return () => parent.setChildOpen(false);
  }, [parent]);

  return null;
}

// The sticky drawer is not a modal: react-aria has no non-modal Modal, so this
// is a fixed panel drawn by hand, open and closed by the Drawer's own state.
// It stays in the page until its exit animation has played.
function StickyPanel({
  className,
  isKeyboardDismissDisabled,
  children,
}: {
  className: string;
  isKeyboardDismissDisabled?: boolean;
  children: ReactNode;
}) {
  const state = useContext(OverlayTriggerStateContext);
  const isOpen = state?.isOpen ?? false;
  const [mounted, setMounted] = useState(false);
  const [present, setPresent] = useState(false);
  const opener = useRef<HTMLElement | null>(null);

  useEffect(() => setMounted(true), []);

  // Remember what had focus before the panel took it, to give it back. A
  // button that was pressed does not always have focus (Safari does not give
  // it), so the button that is now expanded stands in for it.
  useLayoutEffect(() => {
    if (!isOpen) return;
    const active = document.activeElement as HTMLElement | null;
    const expanded = document.querySelectorAll<HTMLElement>(
      'button[aria-expanded="true"]',
    );
    opener.current =
      active && active !== document.body ? active : (expanded[0] ?? null);
    setPresent(true);
  }, [isOpen]);

  useEffect(() => {
    if (isOpen || !opener.current) return;
    opener.current.focus();
    opener.current = null;
  }, [isOpen]);

  // Normally the end of the exit animation removes it. This covers the cases
  // where there is none: reduced motion, or the animation styles left out.
  useEffect(() => {
    if (isOpen || !present) return;
    const reduced = window.matchMedia(
      "(prefers-reduced-motion: reduce)",
    ).matches;
    const timer = window.setTimeout(() => setPresent(false), reduced ? 0 : 500);
    return () => window.clearTimeout(timer);
  }, [isOpen, present]);

  if (!mounted || !present) return null;

  return createPortal(
    // biome-ignore lint/a11y/noStaticElementInteractions: only listens for Escape bubbling up from the dialog inside
    <div
      data-entering={isOpen || undefined}
      data-exiting={!isOpen || undefined}
      onAnimationEnd={(event) => {
        if (event.target === event.currentTarget && !isOpen) setPresent(false);
      }}
      onKeyDown={(event) => {
        if (event.key === "Escape" && !isKeyboardDismissDisabled) {
          event.stopPropagation();
          state?.close();
        }
      }}
      className={className}
    >
      {children}
    </div>,
    document.body,
  );
}

/**
 * The drawer: a dimmed backdrop and a panel on one edge. Put a `DrawerHeader`
 * with a `DrawerTitle`, a `DrawerBody` and a `DrawerFooter` inside. It slides
 * in and out, and not for people who prefer reduced motion.
 *
 * Pick a `variant` for its look. `sticky` is the odd one out: it is not a
 * modal, has no backdrop, and leaves the page usable.
 */
export function DrawerContent({
  children,
  variant = "default",
  placement = "right",
  size,
  isDismissable = true,
  isKeyboardDismissDisabled,
  showCloseButton = true,
  className,
  ...props
}: DrawerContentProps) {
  const parent = useDrawerContext();
  const [hasChild, setHasChild] = useState(false);
  const styles = drawerStyles({ placement, size, variant, hasChild });
  const value = useMemo(
    () => ({ variant, setChildOpen: setHasChild }),
    [variant],
  );

  const dialog = (
    <DrawerProvider value={value}>
      {parent ? <RegisterWithParent parent={parent} /> : null}
      <AriaDialog aria-label={props["aria-label"]} className={styles.dialog()}>
        {(options) => (
          <>
            {typeof children === "function" ? children(options) : children}
            {showCloseButton ? (
              <Button
                slot="close"
                isIcon
                variant="ghost"
                size="xs"
                aria-label="Close"
                className={styles.close()}
              >
                <XIcon />
              </Button>
            ) : null}
          </>
        )}
      </AriaDialog>
    </DrawerProvider>
  );

  if (variant === "sticky") {
    return (
      <StickyPanel
        className={cn(styles.panel(), className)}
        isKeyboardDismissDisabled={isKeyboardDismissDisabled}
      >
        {dialog}
      </StickyPanel>
    );
  }

  return (
    <ModalOverlay
      isDismissable={isDismissable}
      isKeyboardDismissDisabled={isKeyboardDismissDisabled}
      className={styles.overlay()}
    >
      <Modal className={cn(styles.panel(), className)}>{dialog}</Modal>
    </ModalOverlay>
  );
}

const partStyles = drawerStyles();

interface PartProps {
  children: ReactNode;
  className?: string;
}

/** The top of the drawer: the title and, under it, a line that says more. */
export function DrawerHeader({ children, className }: PartProps) {
  return <div className={cn(partStyles.header(), className)}>{children}</div>;
}

/** The heading of the drawer. It also names the drawer for screen readers. */
export function DrawerTitle({ children, className }: PartProps) {
  return (
    <Heading slot="title" className={cn(partStyles.title(), className)}>
      {children}
    </Heading>
  );
}

/** A line under the title that says what the drawer is for. */
export function DrawerDescription({ children, className }: PartProps) {
  return <p className={cn(partStyles.description(), className)}>{children}</p>;
}

/**
 * The middle of the drawer. It scrolls when the content is taller than the
 * drawer.
 */
export function DrawerBody({ children, className }: PartProps) {
  return <div className={cn(partStyles.body(), className)}>{children}</div>;
}

/** The bottom of the drawer: its buttons, ending at the right. It stays in view while the body scrolls. */
export function DrawerFooter({ children, className }: PartProps) {
  return <div className={cn(partStyles.footer(), className)}>{children}</div>;
}

/**
 * A button that closes the drawer it is in. It is a `Button`, so it takes the
 * same variants and sizes, and `onPress` runs before the drawer closes.
 */
export function DrawerClose({
  variant = "outline",
  ...props
}: Omit<ButtonProps, "slot" | "href">) {
  return <Button slot="close" variant={variant} {...props} />;
}

It imports XIcon from @/components/icons. Add the icon, or swap it for your own.

3. Add the animations

In src/app/globals.css copy the drawer-in and drawer-out keyframes, the .drawer-modal rules for [data-entering] and [data-exiting], and the reduced-motion rule that turns them off. The backdrop fades with the .dialog-overlay rules and keyframes from Dialog, so copy those too. Without them the drawer still works, it just appears and disappears at once.

4. Use it

import {
  Drawer,
  DrawerBody,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
} from "@/components/ui/drawer/drawer";

Anatomy

A trigger, and a panel on one edge with a header, a body and a footer.

<Drawer>
  <Button>Open</Button>
  <DrawerContent placement="right">
    <DrawerHeader>
      <DrawerTitle>Order #1042</DrawerTitle>
      <DrawerDescription>Placed on 3 March.</DrawerDescription>
    </DrawerHeader>
    <DrawerBody>{/* anything */}</DrawerBody>
    <DrawerFooter>
      <DrawerClose>Close</DrawerClose>
    </DrawerFooter>
  </DrawerContent>
</Drawer>
PartRendered asNotes
Drawerno elementHolds whether it is open. It has no look: put the button that opens it, and a DrawerContent, inside.
DrawerContentbackdrop and panelThe dimmed backdrop and the panel on one edge. The page behind cannot be used, and Tab stays inside the panel.
DrawerHeader / DrawerTitle / DrawerDescriptiondiv, heading, pThe top: a title that also names the drawer for screen readers, and a line under it.
DrawerBodydivThe middle. It scrolls when the content is taller than the drawer.
DrawerFooterdivThe buttons, at the bottom. It stays in view while the body scrolls.
DrawerCloseButtonA button that closes the drawer.
X buttonButtonIn the corner, unless showCloseButton is false.

Examples

Press a button to open its drawer.

Usage

Variants

Four looks, chosen with variant. Default is a panel flush with an edge. Floating is detached from the edges, with a border and rounded on every corner. Sticky is not a modal. Nested is for a drawer opened from another drawer.

Sticky

A sticky drawer is not a modal. There is no backdrop, the page behind is not locked or hidden from screen readers, and clicking outside does not close it. It stays until its X, a DrawerClose or Escape (while focus is inside it) closes it. Open it, then type in the field on the page.

Nested

Open a drawer from inside another. Give the inner one variant nested: its backdrop is lighter, it leaves a strip of the first drawer showing on a narrow screen, and the drawer under it steps back and shrinks a little. Closing it brings the first one forward again.

Placement

The edge it slides in from. Right is the default, for details and forms. Left is for navigation, and bottom makes a sheet on a phone.

Sizes

On the sides, the width. On the top and the bottom, the most it grows: it is as tall as its content until then.

Scrolling

A drawer whose content is taller than the screen scrolls its body, and keeps the header and the footer in view.

Bottom sheet

A drawer at the bottom has rounded top corners and is as tall as its content. Try it on a phone.

Dismissing

A drawer closes on Escape and on a click outside, plus its buttons. isDismissable turns off the click outside, and isKeyboardDismissDisabled turns off Escape. Then only its buttons close it, so leave one.

Without the X

showCloseButton hides the X in the corner. Keep a button in the footer.

Controlled

Keep whether it is open in your own state, to open it from anywhere: a menu item, a keyboard shortcut, the result of a request.

isOpen: false

Filters form

Children can be a function that receives close. Here the form closes the drawer when it is submitted.

No filters applied.

Component API

Drawer is made of the parts below.

Drawer

PropTypeDefault
childrenReactNode- (the trigger and a DrawerContent)
isOpenboolean-
defaultOpenbooleanfalse
onOpenChange(isOpen: boolean) => void-

DrawerContent

PropTypeDefault
childrenReactNode | ({ close }) => ReactNode- (required)
variant"default" | "floating" | "sticky" | "nested""default"
placement"right" | "left" | "top" | "bottom""right"
size"sm" | "md" | "lg" | "xl" | "full""md"
isDismissablebooleantrue
isKeyboardDismissDisabledbooleanfalse
showCloseButtonbooleantrue
aria-labelstring- (when there is no DrawerTitle)
classNamestring-

The other parts

PartProps
DrawerHeader, DrawerTitle, DrawerDescriptionchildren, className
DrawerBody, DrawerFooterchildren, className
DrawerCloseany Button prop except slot and href, such as variant and onPress