Sheet
A panel pinned to one edge of the screen, for filters, details and forms that should not take you off the page.
Installation
Copy and paste the following code into your project.
1'use client';23import { AnimatePresence, type HTMLMotionProps, motion, useReducedMotion } from 'motion/react';4import * as React from 'react';5import { createPortal } from 'react-dom';6import { cn } from '../lib/cn';7import {8 assignRef,9 focusFirst,10 lockPageScroll,11 trapFocus,12 useIsClient,13 useLayer,14} from '../lib/overlay';15import { backdrop, reveal, slideVariants, springs, tap } from '../lib/motion';16import { useControllableState } from '../lib/use-controllable-state';1718type IconProps = React.SVGProps<SVGSVGElement> & {19 size?: number | string;20};2122function XIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {23 return (24 <svg25 xmlns="http://www.w3.org/2000/svg"26 width={size}27 height={size}28 viewBox="0 0 24 24"29 fill="none"30 stroke="currentColor"31 strokeWidth={strokeWidth}32 strokeLinecap="round"33 strokeLinejoin="round"34 aria-hidden="true"35 {...props}36 >37 <path d="M18 6 6 18" />38 <path d="m6 6 12 12" />39 </svg>40 );41}4243type SheetSide = 'top' | 'bottom' | 'left' | 'right';44type SheetSize = 'sm' | 'md' | 'lg' | 'xl' | 'full';4546const SIDE_CLASSES: Record<SheetSide, string> = {47 right:48 'inset-y-0 right-0 h-full pt-[env(safe-area-inset-top)] pr-[env(safe-area-inset-right)] pb-[env(safe-area-inset-bottom)]',49 left: 'inset-y-0 left-0 h-full pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)] pl-[env(safe-area-inset-left)]',50 top: 'inset-x-0 top-0 w-full pt-[env(safe-area-inset-top)] pr-[env(safe-area-inset-right)] pl-[env(safe-area-inset-left)]',51 bottom:52 'inset-x-0 bottom-0 w-full pr-[env(safe-area-inset-right)] pb-[env(safe-area-inset-bottom)] pl-[env(safe-area-inset-left)]',53};5455const CLOSE_TOP: Record<SheetSide, string> = {56 right: 'top-[calc(1rem+env(safe-area-inset-top))]',57 left: 'top-[calc(1rem+env(safe-area-inset-top))]',58 top: 'top-[calc(1rem+env(safe-area-inset-top))]',59 bottom: 'top-4',60};6162const CLOSE_RIGHT: Record<SheetSide, string> = {63 right: 'right-[calc(1rem+env(safe-area-inset-right))]',64 left: 'right-4',65 top: 'right-[calc(1rem+env(safe-area-inset-right))]',66 bottom: 'right-[calc(1rem+env(safe-area-inset-right))]',67};6869type SlotChildProps = Record<string, unknown> & { ref?: React.Ref<HTMLElement> };7071function mergeSlotProps(own: Record<string, unknown>, child: SlotChildProps) {72 const merged: Record<string, unknown> = { ...own, ...child };73 for (const [key, ownValue] of Object.entries(own)) {74 const childValue = child[key];75 if (76 /^on[A-Z]/.test(key) &&77 typeof ownValue === 'function' &&78 typeof childValue === 'function'79 ) {80 merged[key] = (...args: unknown[]) => {81 childValue(...args);82 ownValue(...args);83 };84 }85 }86 if (own.className || child.className) {87 merged.className = cn(88 own.className as string | undefined,89 child.className as string | undefined,90 );91 }92 if (own.style || child.style) {93 merged.style = { ...(own.style as object | undefined), ...(child.style as object | undefined) };94 }95 return merged;96}9798function useComposedRef<T extends HTMLElement>(99 first: React.Ref<T> | undefined,100 second: React.Ref<T> | React.Ref<HTMLElement> | undefined,101) {102 return React.useCallback(103 (node: T | null) => {104 assignRef(first, node);105 assignRef(second as React.Ref<T> | undefined, node);106 },107 [first, second],108 );109}110111const HORIZONTAL_SIZE: Record<SheetSize, string> = {112 sm: 'w-80',113 md: 'w-96',114 lg: 'w-[32rem]',115 xl: 'w-[40rem]',116 full: 'w-full',117};118119const VERTICAL_SIZE: Record<SheetSize, string> = {120 sm: 'max-h-[40dvh]',121 md: 'max-h-[60dvh]',122 lg: 'max-h-[80dvh]',123 xl: 'max-h-[92dvh]',124 full: 'h-dvh',125};126127const OVERLAY_STYLE = { willChange: 'opacity' } as const;128const PANEL_STYLE = { willChange: 'transform' } as const;129130interface SheetContextValue {131 open: boolean;132 setOpen: (open: boolean) => void;133 id: string;134 hasTitle: boolean;135 setHasTitle: (value: boolean) => void;136 hasDescription: boolean;137 setHasDescription: (value: boolean) => void;138}139140const SheetContext = React.createContext<SheetContextValue | null>(null);141142const useSheetContext = (): SheetContextValue => {143 const context = React.use(SheetContext);144 if (!context) {145 throw new Error('Sheet components must be used within Sheet');146 }147 return context;148};149150interface SheetProps {151 children: React.ReactNode;152 defaultOpen?: boolean;153 open?: boolean;154 onOpenChange?: (open: boolean) => void;155}156157interface SheetTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {158 asChild?: boolean;159}160161interface SheetContentProps extends Omit<HTMLMotionProps<'div'>, 'children'> {162 children: React.ReactNode;163 side?: SheetSide;164 size?: SheetSize;165 showClose?: boolean;166 closeLabel?: string;167}168169type SheetSectionProps = React.HTMLAttributes<HTMLDivElement>;170type SheetTitleProps = React.HTMLAttributes<HTMLHeadingElement>;171type SheetDescriptionProps = React.HTMLAttributes<HTMLParagraphElement>;172interface SheetCloseProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {173 asChild?: boolean;174}175176const SheetRoot = ({177 children,178 defaultOpen = false,179 open: controlledOpen,180 onOpenChange,181}: SheetProps) => {182 const [open, setOpen] = useControllableState({183 value: controlledOpen,184 defaultValue: defaultOpen,185 onChange: onOpenChange,186 });187 const [hasTitle, setHasTitle] = React.useState(false);188 const [hasDescription, setHasDescription] = React.useState(false);189 const id = React.useId();190191 React.useEffect(() => {192 if (!open) return;193 return lockPageScroll();194 }, [open]);195196 const value = React.useMemo<SheetContextValue>(197 () => ({ open, setOpen, id, hasTitle, setHasTitle, hasDescription, setHasDescription }),198 [open, setOpen, id, hasTitle, hasDescription],199 );200201 return <SheetContext value={value}>{children}</SheetContext>;202};203204SheetRoot.displayName = 'Sheet';205206const SheetTrigger = ({207 asChild = false,208 children,209 onClick,210 ref,211 ...props212}: SheetTriggerProps & { ref?: React.Ref<HTMLButtonElement> }) => {213 const { open, setOpen, id } = useSheetContext();214 const slot = asChild && React.isValidElement<SlotChildProps>(children) ? children : null;215 const composedRef = useComposedRef<HTMLButtonElement>(ref, slot?.props.ref);216217 const a11y = {218 'aria-haspopup': 'dialog' as const,219 'aria-expanded': open,220 'aria-controls': `${id}-content`,221 };222223 const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {224 onClick?.(event);225 setOpen(true);226 };227228 if (slot) {229 return React.cloneElement(slot, {230 ...mergeSlotProps({ ...props, onClick: handleClick }, slot.props),231 ...a11y,232 ref: composedRef,233 });234 }235236 return (237 <button ref={ref} type="button" onClick={handleClick} {...a11y} {...props}>238 {children}239 </button>240 );241};242243SheetTrigger.displayName = 'SheetTrigger';244245const SheetOverlay = ({ className }: { className?: string }) => {246 const { setOpen } = useSheetContext();247 const shouldReduceMotion = useReducedMotion();248249 return (250 <motion.div251 variants={shouldReduceMotion ? reveal : backdrop}252 initial="hidden"253 animate="visible"254 exit="exit"255 style={OVERLAY_STYLE}256 className={cn('bg-overlay fixed inset-0 z-500 backdrop-blur-xs', className)}257 onClick={() => setOpen(false)}258 />259 );260};261262const SheetContent = ({263 children,264 className,265 side = 'right',266 size = 'md',267 showClose = true,268 closeLabel = 'Close',269 ref,270 ...props271}: SheetContentProps & { ref?: React.Ref<HTMLDivElement> }) => {272 const { open, setOpen, id, hasTitle, hasDescription } = useSheetContext();273 const mounted = useIsClient();274 const contentRef = React.useRef<HTMLDivElement>(null);275 const composedRef = useComposedRef<HTMLDivElement>(contentRef, ref);276 const layer = useLayer(open, true);277 const restoreRef = React.useRef<HTMLElement | null>(null);278 const shouldReduceMotion = useReducedMotion();279280 React.useEffect(() => {281 if (!open) return;282283 restoreRef.current = document.activeElement as HTMLElement;284285 const onKeyDown = (event: KeyboardEvent) => {286 if (event.defaultPrevented) return;287 const content = contentRef.current;288 if (!content) return;289290 if (event.key === 'Escape') {291 if (!layer.isTopmost()) return;292 event.preventDefault();293 setOpen(false);294 return;295 }296 if (layer.isTopmostModal() && !layer.isInsideUpperLayer(event.target))297 trapFocus(event, content);298 };299300 document.addEventListener('keydown', onKeyDown);301302 const frame = requestAnimationFrame(() => {303 if (contentRef.current) focusFirst(contentRef.current);304 });305306 return () => {307 cancelAnimationFrame(frame);308 document.removeEventListener('keydown', onKeyDown);309 restoreRef.current?.focus();310 };311 }, [open, setOpen, layer]);312313 if (!mounted) return null;314315 const horizontal = side === 'left' || side === 'right';316317 const sheet = (318 <AnimatePresence>319 {open && (320 <>321 <SheetOverlay />322 <motion.div323 ref={composedRef}324 id={`${id}-content`}325 role="dialog"326 aria-modal="true"327 aria-labelledby={hasTitle ? `${id}-title` : undefined}328 aria-describedby={hasDescription ? `${id}-description` : undefined}329 tabIndex={-1}330 data-side={side}331 data-size={size}332 variants={shouldReduceMotion ? reveal : slideVariants[side]}333 initial="hidden"334 animate="visible"335 exit="exit"336 style={PANEL_STYLE}337 className={cn(338 'bg-popover text-popover-foreground fixed z-500 flex max-w-full flex-col shadow-lg outline-none',339 SIDE_CLASSES[side],340 horizontal ? HORIZONTAL_SIZE[size] : VERTICAL_SIZE[size],341 className,342 )}343 {...props}344 >345 {showClose && (346 <motion.button347 type="button"348 aria-label={closeLabel}349 onClick={() => setOpen(false)}350 whileTap={shouldReduceMotion ? undefined : tap}351 transition={springs.snappy}352 className={cn(353 'text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-ring absolute z-10 rounded-full p-2 transition-colors focus-visible:ring-2 focus-visible:outline-none',354 CLOSE_TOP[side],355 CLOSE_RIGHT[side],356 )}357 >358 <XIcon size={16} />359 </motion.button>360 )}361 {children}362 </motion.div>363 </>364 )}365 </AnimatePresence>366 );367368 return createPortal(sheet, document.body);369};370371SheetContent.displayName = 'SheetContent';372373const SheetHeader = ({374 className,375 ref,376 ...props377}: SheetSectionProps & { ref?: React.Ref<HTMLDivElement> }) => {378 return <div ref={ref} className={cn('flex flex-col gap-1 p-6 pr-14', className)} {...props} />;379};380381SheetHeader.displayName = 'SheetHeader';382383const SheetBody = ({384 className,385 ref,386 ...props387}: SheetSectionProps & { ref?: React.Ref<HTMLDivElement> }) => {388 return <div ref={ref} className={cn('flex-1 overflow-y-auto px-6 pb-6', className)} {...props} />;389};390391SheetBody.displayName = 'SheetBody';392393const SheetFooter = ({394 className,395 ref,396 ...props397}: SheetSectionProps & { ref?: React.Ref<HTMLDivElement> }) => {398 return (399 <div400 ref={ref}401 className={cn(402 'border-border mt-auto flex items-center justify-end gap-2 border-t px-6 py-4',403 className,404 )}405 {...props}406 />407 );408};409410SheetFooter.displayName = 'SheetFooter';411412const SheetTitle = ({413 className,414 children,415 ref,416 ...props417}: SheetTitleProps & { ref?: React.Ref<HTMLHeadingElement> }) => {418 const { id, setHasTitle } = useSheetContext();419420 React.useEffect(() => {421 setHasTitle(true);422 return () => setHasTitle(false);423 }, [setHasTitle]);424425 return (426 <h2427 ref={ref}428 id={`${id}-title`}429 className={cn('text-lg leading-tight font-semibold tracking-tight', className)}430 {...props}431 >432 {children}433 </h2>434 );435};436437SheetTitle.displayName = 'SheetTitle';438439const SheetDescription = ({440 className,441 ref,442 ...props443}: SheetDescriptionProps & { ref?: React.Ref<HTMLParagraphElement> }) => {444 const { id, setHasDescription } = useSheetContext();445446 React.useEffect(() => {447 setHasDescription(true);448 return () => setHasDescription(false);449 }, [setHasDescription]);450451 return (452 <p453 ref={ref}454 id={`${id}-description`}455 className={cn('text-muted-foreground text-sm', className)}456 {...props}457 />458 );459};460461SheetDescription.displayName = 'SheetDescription';462463const SheetClose = ({464 asChild = false,465 children,466 onClick,467 ref,468 ...props469}: SheetCloseProps & { ref?: React.Ref<HTMLButtonElement> }) => {470 const { setOpen } = useSheetContext();471 const slot = asChild && React.isValidElement<SlotChildProps>(children) ? children : null;472 const composedRef = useComposedRef<HTMLButtonElement>(ref, slot?.props.ref);473474 const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {475 onClick?.(event);476 setOpen(false);477 };478479 if (slot) {480 return React.cloneElement(slot, {481 ...mergeSlotProps({ ...props, onClick: handleClick }, slot.props),482 ref: composedRef,483 });484 }485486 return (487 <button ref={ref} type="button" onClick={handleClick} {...props}>488 {children}489 </button>490 );491};492493SheetClose.displayName = 'SheetClose';494495const Sheet = Object.assign(SheetRoot, {496 Trigger: SheetTrigger,497 Content: SheetContent,498 Header: SheetHeader,499 Body: SheetBody,500 Footer: SheetFooter,501 Title: SheetTitle,502 Description: SheetDescription,503 Close: SheetClose,504});505506export { Sheet };507export type {508 SheetCloseProps,509 SheetContentProps,510 SheetDescriptionProps,511 SheetProps,512 SheetSectionProps,513 SheetSide,514 SheetSize,515 SheetTitleProps,516 SheetTriggerProps,517};
Update the import paths to match your project structure.
Anatomy
1import { Sheet } from '@/components/sheet';
1<Sheet>2 <Sheet.Trigger asChild>3 <Button variant="outline">Filters</Button>4 </Sheet.Trigger>5 <Sheet.Content side="right" size="md">6 <Sheet.Header>7 <Sheet.Title>Filters</Sheet.Title>8 <Sheet.Description>Narrow the list without leaving the page.</Sheet.Description>9 </Sheet.Header>10 <Sheet.Body>...</Sheet.Body>11 <Sheet.Footer>12 <Sheet.Close asChild>13 <Button>Apply</Button>14 </Sheet.Close>15 </Sheet.Footer>16 </Sheet.Content>17</Sheet>
A sheet is flush with the edge it opens from and fills that edge end to end. It traps focus, closes on Escape and on the backdrop, locks page scroll and returns focus to the trigger when it goes.
Sheet or Drawer
They look related and they are, but they answer different questions. Drawer is the touch one: a floating island with a handle you drag to dismiss, at home on a phone. Sheet is the desktop one: a fixed side panel with no drag, sized in steps, meant for a filter rail, an edit form or a details view. If the content is something you fill in, reach for Sheet. If it is something you flick away, reach for Drawer.
Composition
Use the following composition to build a
Sheet:Sheetโโโ Sheet.Triggerโโโ Sheet.Contentโโโ Sheet.Headerโ โโโ Sheet.Titleโ โโโ Sheet.Descriptionโโโ Sheet.Bodyโโโ Sheet.Footerโโโ Sheet.Close
Header, Body and Footer are layout: the body scrolls on its own and the footer sticks to the bottom, so long forms keep their actions in reach.Sides
1'use client';23import { Button } from '@/components/button';4import { Sheet, type SheetSide } from '@/components/sheet';56const SIDES: SheetSide[] = ['left', 'right', 'top', 'bottom'];78export function Sides() {9 return (10 <div className="flex flex-wrap gap-2">11 {SIDES.map((side) => (12 <Sheet key={side}>13 <Sheet.Trigger asChild>14 <Button variant="outline" size="sm" className="capitalize">15 {side}16 </Button>17 </Sheet.Trigger>18 <Sheet.Content side={side}>19 <Sheet.Header>20 <Sheet.Title className="capitalize">{side}</Sheet.Title>21 <Sheet.Description>A sheet anchored to the {side} edge.</Sheet.Description>22 </Sheet.Header>23 <Sheet.Body>24 <p className="text-muted-foreground text-sm">25 Press Escape, click the backdrop or use the close button to dismiss it.26 </p>27 </Sheet.Body>28 </Sheet.Content>29 </Sheet>30 ))}31 </div>32 );33}
Sizes
size is a width on the left and right, and a maximum height on the top and bottom. full covers the screen.1'use client';23import { Button } from '@/components/button';4import { Sheet, type SheetSize } from '@/components/sheet';56const SIZES: SheetSize[] = ['sm', 'md', 'lg', 'xl', 'full'];78export function Sizes() {9 return (10 <div className="flex flex-wrap gap-2">11 {SIZES.map((size) => (12 <Sheet key={size}>13 <Sheet.Trigger asChild>14 <Button variant="outline" size="sm">15 {size}16 </Button>17 </Sheet.Trigger>18 <Sheet.Content size={size}>19 <Sheet.Header>20 <Sheet.Title>Size {size}</Sheet.Title>21 <Sheet.Description>Width on the sides, height on top and bottom.</Sheet.Description>22 </Sheet.Header>23 </Sheet.Content>24 </Sheet>25 ))}26 </div>27 );28}
API Reference
Sheet
| Prop | Type | Default | Description |
|---|---|---|---|
defaultOpen | boolean | false | Open state when uncontrolled |
open | boolean | - | Controlled open state |
onOpenChange | (open: boolean) => void | - | Called when the open state changes |
Sheet.Trigger
| Prop | Type | Default | Description |
|---|---|---|---|
asChild | boolean | false | Render the child as the trigger instead of a button |
className | string | - | Additional CSS classes |
Sheet.Content
| Prop | Type | Default | Description |
|---|---|---|---|
side | 'top' | 'bottom' | 'left' | 'right' | 'right' | Edge the sheet is pinned to |
size | 'sm' | 'md' | 'lg' | 'xl' | 'full' | 'md' | Width on the sides, height top and bottom |
showClose | boolean | true | Show the corner close button |
closeLabel | string | 'Close' | Accessible name of that button |
className | string | - | Additional CSS classes |
Sheet.Close
| Prop | Type | Default | Description |
|---|---|---|---|
asChild | boolean | false | Render the child as the closer instead of a button |
className | string | - | Additional CSS classes |
Sheet.Header / Sheet.Body / Sheet.Footer / Sheet.Title / Sheet.Description
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.