Skip to content

Drawer

A sliding panel that appears from any edge of the screen. Built on Radix UI Dialog with multiple positions and sizes for mobile-friendly interfaces.

Installation

Add Drawer to your project with the CK-UI CLI. It copies the source into your project, so the code is yours to change.

Terminal
npx ck-ui-cli@latest add drawer
Adds
Drawer.tsxThemeScope.tsxto your CK-UI folder (src/components/ck-ui by default)
Installs
@radix-ui/react-dialogreact-iconsif your project does not have them yet

First time with CK-UI in this project? Run npx ck-ui-cli@latest init once before adding components. The installation guide explains what it sets up.

Manual installationInstall the packages and copy the files yourself.

Install the following dependencies

Run these commands in your terminal to install the required packages

Terminal
npm install @radix-ui/react-dialog react-icons

Add the ThemeScope component

Drawer imports ./ThemeScope, so add this file next to it

/components/ui/ThemeScope.tsx
"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

/*
 * A local light/dark boundary. Everything inside renders in `theme`, whatever the site theme is: the semantic tokens
 * (`bg-background`, `text-foreground`, …) and every `dark:` utility resolve to the nearest boundary, not to <html>.
 * Overlays that portal out of the tree (Select, Popover, Tooltip, Dropdown, Modal, AlertDialog, Drawer, Toast) render
 * into a layer that carries the same theme, so a menu opened inside a dark scope is dark too.
 *
 * It never touches <html>, the site's theme state or its storage. Without `theme` it renders no theme class and
 * follows the surrounding theme. Nest at most one scope below the site theme (see `darkMode` in tailwind.config.ts).
 */

export type ScopeTheme = "light" | "dark";

const PortalContainerContext = React.createContext<HTMLElement | null>(null);

/** Where overlays portal to: the nearest themed ThemeScope's layer, or null for the default (document.body). */
export function usePortalContainer() {
    return React.useContext(PortalContainerContext);
}

// A themed layer at the end of <body> for portalled overlays. Only created while the scope sets a theme, so a scope
// that follows the site leaves the document exactly as it was.
function usePortalLayer(theme: ScopeTheme | undefined) {
    const [layer, setLayer] = React.useState<HTMLElement | null>(null);
    const themed = theme !== undefined;

    React.useEffect(() => {
        if (!themed) return;
        const element = document.createElement("div");
        element.setAttribute("data-theme-scope-layer", "");
        document.body.appendChild(element);
        setLayer(element);
        return () => {
            element.remove();
            setLayer(null);
        };
    }, [themed]);

    React.useEffect(() => {
        if (!layer || !theme) return;
        // text-foreground: portalled text that sets no colour of its own resolves against the layer's tokens.
        layer.className = `${theme} text-foreground`;
    }, [layer, theme]);

    return layer;
}

export interface RootProps extends React.HTMLAttributes<HTMLDivElement> {
    /** Theme for this subtree. Leave undefined to follow the surrounding (site) theme. */
    theme?: ScopeTheme;
}

const Root = React.forwardRef<HTMLDivElement, RootProps>(({ theme, className, children, ...props }, ref) => {
    const layer = usePortalLayer(theme);
    // A scope that follows its surroundings keeps the surrounding scope's layer.
    const outerLayer = usePortalContainer();

    return (
        <div ref={ref} data-theme-scope={theme} className={cn(theme && [theme, "text-foreground"], className)} {...props}>
            <PortalContainerContext.Provider value={theme ? layer : outerLayer}>{children}</PortalContainerContext.Provider>
        </div>
    );
});
Root.displayName = "ThemeScope.Root";

export { Root };

Create or update your Drawer component

Copy this code to create your Drawer component

/components/ui/Drawer.tsx
"use client";

import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { RiCloseLine } from "react-icons/ri";
import { cn } from "@/lib/utils";
import { usePortalContainer } from "./ThemeScope";

const useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;

export type DrawerPosition = "left" | "right" | "top" | "bottom";
export type DrawerSize = "xs" | "sm" | "md" | "lg" | "xl" | "full";

interface DrawerContextValue {
    showCloseButton: boolean;
    registerDescription: () => () => void;
}

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

// Size classes for different positions
const sizeClasses: Record<DrawerSize, Record<DrawerPosition, string>> = {
    xs: { left: "w-64", right: "w-64", top: "min-h-64", bottom: "min-h-64" },
    sm: { left: "w-80", right: "w-80", top: "min-h-80", bottom: "min-h-80" },
    md: { left: "w-96", right: "w-96", top: "min-h-96", bottom: "min-h-96" },
    lg: { left: "w-1/3", right: "w-1/3", top: "h-1/2", bottom: "h-1/2" },
    xl: { left: "w-1/2", right: "w-1/2", top: "h-2/3", bottom: "h-2/3" },
    full: { left: "w-full", right: "w-full", top: "h-full", bottom: "h-full" },
};

const positionClasses: Record<DrawerPosition, string> = {
    left: "left-0 top-0 h-full",
    right: "right-0 top-0 h-full",
    top: "top-0 left-0 w-full",
    bottom: "bottom-0 left-0 w-full",
};

const animationClasses: Record<DrawerPosition, string> = {
    left: "data-[state=open]:slide-in-from-left-full data-[state=closed]:slide-out-to-left-full",
    right: "data-[state=open]:slide-in-from-right-full data-[state=closed]:slide-out-to-right-full",
    top: "data-[state=open]:slide-in-from-top-full data-[state=closed]:slide-out-to-top-full",
    bottom: "data-[state=open]:slide-in-from-bottom-full data-[state=closed]:slide-out-to-bottom-full",
};

/** Radix Dialog root: controlled (`open` + `onOpenChange`) or uncontrolled (`defaultOpen`, `Drawer.Trigger`). */
const DrawerRoot = (props: DialogPrimitive.DialogProps) => <DialogPrimitive.Root {...props} />;
DrawerRoot.displayName = "Drawer.Root";

const DrawerTrigger = React.forwardRef<HTMLButtonElement, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Trigger>>((props, ref) => (
    <DialogPrimitive.Trigger ref={ref} {...props} />
));
DrawerTrigger.displayName = "Drawer.Trigger";

const DrawerClose = React.forwardRef<HTMLButtonElement, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Close>>((props, ref) => <DialogPrimitive.Close ref={ref} {...props} />);
DrawerClose.displayName = "Drawer.Close";

const DrawerOverlay = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Overlay>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>>(({ className, ...props }, ref) => (
    <DialogPrimitive.Overlay
        ref={ref}
        className={cn(
            "fixed inset-0 z-drawer bg-overlay backdrop-blur-sm",
            "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
            className
        )}
        {...props}
    />
));
DrawerOverlay.displayName = "Drawer.Overlay";

export interface DrawerContentProps extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
    position?: DrawerPosition;
    size?: DrawerSize;
    /** Renders an icon button labelled "Close" in `Drawer.Header`. */
    showCloseButton?: boolean;
}

/**
 * The drawer panel (`role="dialog"`); `className` goes on it. Render a `Drawer.Title` inside
 * (visually hidden with `className="sr-only"` if needed); `Drawer.Description` is optional.
 */
const DrawerContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>, DrawerContentProps>(
    ({ children, position = "right", size = "md", showCloseButton = false, className, ...props }, ref) => {
        // Only point aria-describedby at Drawer.Description when one is rendered (avoids a dangling reference and Radix's warning).
        const [descriptionCount, setDescriptionCount] = React.useState(0);
        const registerDescription = React.useCallback(() => {
            setDescriptionCount((count) => count + 1);
            return () => setDescriptionCount((count) => count - 1);
        }, []);
        const context = React.useMemo(() => ({ showCloseButton, registerDescription }), [showCloseButton, registerDescription]);
        const describedByProps = descriptionCount > 0 ? {} : { "aria-describedby": undefined };
        const container = usePortalContainer();

        return (
            <DialogPrimitive.Portal container={container}>
                <DrawerOverlay />
                <DialogPrimitive.Content
                    ref={ref}
                    {...describedByProps}
                    className={cn(
                        "fixed z-drawer max-w-full bg-background",
                        positionClasses[position],
                        sizeClasses[size][position],
                        "data-[state=open]:animate-in data-[state=open]:duration-base data-[state=open]:ease-out",
                        "data-[state=closed]:animate-out data-[state=closed]:duration-base data-[state=closed]:ease-in",
                        animationClasses[position],
                        className
                    )}
                    {...props}
                >
                    <DrawerContext.Provider value={context}>
                        <div className="flex h-full w-full flex-col overflow-hidden">{children}</div>
                    </DrawerContext.Provider>
                </DialogPrimitive.Content>
            </DialogPrimitive.Portal>
        );
    }
);
DrawerContent.displayName = "Drawer.Content";

const DrawerTitle = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Title>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>>(({ className, ...props }, ref) => (
    <DialogPrimitive.Title ref={ref} className={cn("size-label-sm", className)} {...props} />
));
DrawerTitle.displayName = "Drawer.Title";

const DrawerDescription = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Description>, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>>(
    ({ className, ...props }, ref) => {
        const register = React.useContext(DrawerContext)?.registerDescription;
        useIsomorphicLayoutEffect(() => register?.(), [register]);

        return <DialogPrimitive.Description ref={ref} className={cn("size-p-xs text-muted-foreground", className)} {...props} />;
    }
);
DrawerDescription.displayName = "Drawer.Description";

export interface DrawerHeaderProps extends React.HTMLAttributes<HTMLDivElement> {
    /** Overrides `showCloseButton` from `Drawer.Content` for this header. */
    showCloseButton?: boolean;
}

const DrawerHeader = React.forwardRef<HTMLDivElement, DrawerHeaderProps>(({ className, children, showCloseButton: showCloseButtonProp, ...props }, ref) => {
    const context = React.useContext(DrawerContext);
    const showCloseButton = showCloseButtonProp ?? context?.showCloseButton ?? false;

    return (
        <div ref={ref} className={cn("flex items-center gap-3 border-b border-border p-5", className)} {...props}>
            <div className="flex-1">{children}</div>

            {showCloseButton && (
                <DialogPrimitive.Close
                    aria-label="Close"
                    className="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors duration-fast ease-standard hover:bg-muted hover:text-foreground focus-ring"
                >
                    <RiCloseLine aria-hidden="true" className="size-5" />
                </DialogPrimitive.Close>
            )}
        </div>
    );
});
DrawerHeader.displayName = "Drawer.Header";

const DrawerBody = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
    <div ref={ref} className={cn("flex-1 overflow-y-auto p-5", className)} {...props} />
));
DrawerBody.displayName = "Drawer.Body";

const DrawerFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
    <div ref={ref} className={cn("flex items-center gap-4 border-t border-border p-5", className)} {...props} />
));
DrawerFooter.displayName = "Drawer.Footer";

interface DrawerIconProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "children"> {
    children: React.ReactNode;
}

const DrawerIcon = React.forwardRef<HTMLDivElement, DrawerIconProps>(({ className, children, ...props }, ref) => (
    <div ref={ref} aria-hidden="true" className={cn("flex size-10 shrink-0 items-center justify-center rounded-full bg-primary-subtle text-primary-strong", className)} {...props}>
        {children}
    </div>
));
DrawerIcon.displayName = "Drawer.Icon";

export {
    DrawerRoot as Root,
    DrawerTrigger as Trigger,
    DrawerClose as Close,
    DrawerContent as Content,
    DrawerHeader as Header,
    DrawerFooter as Footer,
    DrawerTitle as Title,
    DrawerDescription as Description,
    DrawerBody as Body,
    DrawerIcon as Icon,
};

export const Drawer = {
    Root: DrawerRoot,
    Trigger: DrawerTrigger,
    Close: DrawerClose,
    Content: DrawerContent,
    Header: DrawerHeader,
    Footer: DrawerFooter,
    Title: DrawerTitle,
    Description: DrawerDescription,
    Body: DrawerBody,
    Icon: DrawerIcon,
};

export default Drawer;

Test Your Component

  • 1. Add the component to a test page
  • 2. Check all props and variants work as expected
  • 3. Verify responsive behavior
  • 4. Test with different content/data
  • 5. Ensure accessibility features work correctly

Positions

Drawers can slide in from any side of the screen: left, right, top, or bottom to accommodate different UI requirements.

API Reference

The Drawer component is built on top of the Radix UI Dialog primitive and extends its functionality with additional positioning options and styling.

Drawer.Root

The container component that provides the main drawer functionality.

See Radix UI docs for base props.

PropTypeDefaultDescription
open"boolean""undefined"

The controlled open state of the drawer.

onOpenChange"function""undefined"

Event handler called when the open state of the drawer changes.

defaultOpen"boolean""false"

The open state of the drawer when it is initially rendered.

Drawer.Content

The component that contains the drawer content and handles positioning and animations.

See Radix UI docs for base props.

PropTypeDefaultDescription
position
"left""right""top""bottom"
"right"

The position from which the drawer slides in.

size
"xs""sm""md""lg""xl""full"
"md"

The size of the drawer, affecting width or height depending on position.

showCloseButton"boolean""false"

Whether to show a close button (accessible name "Close") in Drawer.Header.

className"string""undefined"

Additional CSS classes for the drawer panel (the element with role="dialog").

Drawer.Header

The header section of the drawer, typically containing a title and optional close button.

PropTypeDefaultDescription
showCloseButton"boolean""from Drawer.Content"

Whether to show a close button in the header. Overrides the value from Drawer.Content.

className"string""undefined"

Additional CSS classes to apply to the header.

Drawer.Body

The main content area of the drawer with automatic overflow handling.

PropTypeDefaultDescription
className"string""undefined"

Additional CSS classes to apply to the body.

The footer section of the drawer, typically containing action buttons.

PropTypeDefaultDescription
className"string""undefined"

Additional CSS classes to apply to the footer.

Drawer.Title

The title component for the drawer header. Every drawer needs one: it names the dialog for screen readers. Hide it visually with className="sr-only" if needed.

See Radix UI docs for base props.

PropTypeDefaultDescription
className"string""undefined"

Additional CSS classes to apply to the title.

Drawer.Description

The optional description component for the drawer header. When rendered, the dialog references it with aria-describedby.

See Radix UI docs for base props.

PropTypeDefaultDescription
className"string""undefined"

Additional CSS classes to apply to the description.

Used in these blocks

Block families with at least one block built on this component. Each page previews its blocks and lists the components and packages they use.

Marketing