Drawer
Contexto lateral. Preservar estado de página. UX móvil impecable.
Instalación
Copia y pega el siguiente código en tu proyecto.
1'use client';23import { cva, type VariantProps } from 'class-variance-authority';4import {5 AnimatePresence,6 type HTMLMotionProps,7 motion,8 useDragControls,9 useMotionValue,10 useReducedMotion,11} from 'motion/react';12import * as React from 'react';13import { createPortal } from 'react-dom';14import { cn } from '../lib/cn';15import {16 assignRef,17 focusFirst,18 lockPageScroll,19 trapFocus,20 useIsClient,21 useLayer,22} from '../lib/overlay';23import { backdrop, reveal, slideVariants } from '../lib/motion';24import { useControllableState } from '../lib/use-controllable-state';25import { Button, type ButtonProps } from './button';2627type IconProps = React.SVGProps<SVGSVGElement> & {28 size?: number | string;29};3031function XIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {32 return (33 <svg34 xmlns="http://www.w3.org/2000/svg"35 width={size}36 height={size}37 viewBox="0 0 24 24"38 fill="none"39 stroke="currentColor"40 strokeWidth={strokeWidth}41 strokeLinecap="round"42 strokeLinejoin="round"43 aria-hidden="true"44 {...props}45 >46 <path d="M18 6 6 18" />47 <path d="m6 6 12 12" />48 </svg>49 );50}5152const DRAWER_OVERLAY_STYLE = { willChange: 'opacity' } as const;53const DRAWER_CONTENT_STYLE = { willChange: 'transform' } as const;54const CLOSE_BUTTON_TAP = { scale: 0.9 } as const;55const SWIPE_CLOSE_THRESHOLD = 80;5657type DrawerContextProps = {58 open: boolean;59 setOpen: React.Dispatch<React.SetStateAction<boolean>>;60 id: string;61 hasTitle: boolean;62 setHasTitle: (value: boolean) => void;63 hasDescription: boolean;64 setHasDescription: (value: boolean) => void;65};6667const DrawerContext = React.createContext<DrawerContextProps | null>(null);6869function useDrawerContext() {70 const ctx = React.use(DrawerContext);71 if (!ctx) throw new Error('Drawer components must be inside <Drawer>.');72 return ctx;73}7475interface DrawerProps {76 children: React.ReactNode;77 defaultOpen?: boolean;78 open?: boolean;79 onOpenChange?: (open: boolean) => void;80}8182const DrawerRoot = ({83 children,84 defaultOpen = false,85 open: controlledOpen,86 onOpenChange,87}: DrawerProps) => {88 const [open, setOpen] = useControllableState({89 value: controlledOpen,90 defaultValue: defaultOpen,91 onChange: onOpenChange,92 });93 const [hasTitle, setHasTitle] = React.useState(false);94 const [hasDescription, setHasDescription] = React.useState(false);95 const id = React.useId();9697 React.useEffect(() => {98 if (!open) return;99 return lockPageScroll();100 }, [open]);101102 const value = React.useMemo<DrawerContextProps>(103 () => ({ open, setOpen, id, hasTitle, setHasTitle, hasDescription, setHasDescription }),104 [open, setOpen, id, hasTitle, hasDescription],105 );106107 return <DrawerContext value={value}>{children}</DrawerContext>;108};109110const DrawerTrigger = ({ children, className, variant, size, onClick, ...props }: ButtonProps) => {111 const { open, setOpen } = useDrawerContext();112113 return (114 <Button115 className={className}116 aria-haspopup="dialog"117 aria-expanded={open}118 onClick={(e) => {119 onClick?.(e);120 setOpen(true);121 }}122 variant={variant}123 size={size}124 {...props}125 >126 {children}127 </Button>128 );129};130131const DrawerOverlay = ({ className }: { className?: string }) => {132 const { setOpen } = useDrawerContext();133 const shouldReduceMotion = useReducedMotion();134135 return (136 <motion.div137 variants={shouldReduceMotion ? reveal : backdrop}138 initial="hidden"139 animate="visible"140 exit="exit"141 style={DRAWER_OVERLAY_STYLE}142 className={cn('bg-overlay fixed inset-0 z-500 backdrop-blur-xs', className)}143 onClick={() => setOpen(false)}144 />145 );146};147148const drawerVariants = cva(149 'fixed z-500 flex flex-col overflow-hidden bg-popover text-popover-foreground shadow-lg rounded-2xl',150 {151 variants: {152 side: {153 bottom:154 'bottom-[max(0.75rem,env(safe-area-inset-bottom))] left-[max(0.75rem,env(safe-area-inset-left))] right-[max(0.75rem,env(safe-area-inset-right))] max-h-[calc(100dvh-max(0.75rem,env(safe-area-inset-top))-max(0.75rem,env(safe-area-inset-bottom)))]',155 top: 'top-[max(0.75rem,env(safe-area-inset-top))] left-[max(0.75rem,env(safe-area-inset-left))] right-[max(0.75rem,env(safe-area-inset-right))] max-h-[calc(100dvh-max(0.75rem,env(safe-area-inset-top))-max(0.75rem,env(safe-area-inset-bottom)))]',156 left: 'left-[max(0.75rem,env(safe-area-inset-left))] top-[max(0.75rem,env(safe-area-inset-top))] bottom-[max(0.75rem,env(safe-area-inset-bottom))] w-[85vw] sm:w-96',157 right:158 'right-[max(0.75rem,env(safe-area-inset-right))] top-[max(0.75rem,env(safe-area-inset-top))] bottom-[max(0.75rem,env(safe-area-inset-bottom))] w-[85vw] sm:w-96',159 },160 },161 defaultVariants: {162 side: 'bottom',163 },164 },165);166167interface DrawerContentProps168 extends Omit<HTMLMotionProps<'div'>, 'children'>, VariantProps<typeof drawerVariants> {169 children: React.ReactNode;170 showDragHandle?: boolean;171 showClose?: boolean;172 closeLabel?: string;173}174175const DrawerContent = ({176 children,177 className,178 side = 'bottom',179 showDragHandle = true,180 showClose = true,181 closeLabel = 'Close',182 ref,183 ...props184}: DrawerContentProps & { ref?: React.Ref<HTMLDivElement> }) => {185 const { open, setOpen, id, hasTitle, hasDescription } = useDrawerContext();186 const mounted = useIsClient();187 const contentRef = React.useRef<HTMLDivElement>(null);188 const layer = useLayer(open, true);189 const triggerRef = React.useRef<HTMLElement | null>(null);190191 const dragY = useMotionValue(0);192 const dragX = useMotionValue(0);193 const dragControls = useDragControls();194 const shouldReduceMotion = useReducedMotion();195196 React.useEffect(() => {197 if (!open) return;198199 triggerRef.current = document.activeElement as HTMLElement;200201 const handleKeyDown = (e: KeyboardEvent) => {202 if (e.defaultPrevented) return;203 const content = contentRef.current;204 if (!content) return;205206 if (e.key === 'Escape') {207 if (!layer.isTopmost()) return;208 e.preventDefault();209 setOpen(false);210 return;211 }212 if (layer.isTopmostModal() && !layer.isInsideUpperLayer(e.target)) trapFocus(e, content);213 };214215 document.addEventListener('keydown', handleKeyDown);216217 const frame = requestAnimationFrame(() => {218 if (contentRef.current) focusFirst(contentRef.current);219 });220221 return () => {222 cancelAnimationFrame(frame);223 document.removeEventListener('keydown', handleKeyDown);224 triggerRef.current?.focus();225 };226 }, [open, setOpen, layer]);227228 const isVertical = side === 'bottom' || side === 'top';229 const isHorizontal = side === 'left' || side === 'right';230231 const dragAxis = isVertical ? 'y' : 'x';232233 const dragConstraints = React.useMemo(() => {234 if (side === 'bottom') return { top: 0, bottom: 0 };235 if (side === 'top') return { top: 0, bottom: 0 };236 if (side === 'left') return { left: 0, right: 0 };237 if (side === 'right') return { left: 0, right: 0 };238 return {};239 }, [side]);240241 const dragElastic = 0.15;242243 const handleDragEnd = (_: unknown, info: { offset: { x: number; y: number } }) => {244 const { x, y } = info.offset;245246 const shouldClose =247 (side === 'bottom' && y > SWIPE_CLOSE_THRESHOLD) ||248 (side === 'top' && -y > SWIPE_CLOSE_THRESHOLD) ||249 (side === 'right' && x > SWIPE_CLOSE_THRESHOLD) ||250 (side === 'left' && -x > SWIPE_CLOSE_THRESHOLD);251252 if (shouldClose) {253 setOpen(false);254 } else {255 if (isVertical) dragY.set(0);256 if (isHorizontal) dragX.set(0);257 }258 };259260 if (!mounted) return null;261262 const drawer = (263 <AnimatePresence>264 {open && (265 <>266 <DrawerOverlay />267 <motion.div268 ref={(node: HTMLDivElement | null) => {269 contentRef.current = node;270 assignRef(ref, node);271 }}272 role="dialog"273 aria-modal="true"274 aria-labelledby={hasTitle ? `${id}-title` : undefined}275 aria-describedby={hasDescription ? `${id}-description` : undefined}276 tabIndex={-1}277 drag={dragAxis}278 dragControls={dragControls}279 dragListener={false}280 dragMomentum={false}281 dragElastic={dragElastic}282 dragConstraints={dragConstraints}283 onDragEnd={handleDragEnd}284 style={{285 ...(isVertical ? { y: dragY } : { x: dragX }),286 ...DRAWER_CONTENT_STYLE,287 }}288 variants={289 shouldReduceMotion ? reveal : slideVariants[side as keyof typeof slideVariants]290 }291 initial="hidden"292 animate="visible"293 exit="exit"294 className={cn(drawerVariants({ side }), className)}295 {...props}296 >297 <div298 className="shrink-0 touch-none select-none"299 onPointerDown={(event) => dragControls.start(event)}300 >301 {showDragHandle && (302 <div aria-hidden="true" className="flex items-center justify-center py-2.5">303 <div className="bg-muted-foreground/30 h-1 w-10 cursor-grab rounded-full active:cursor-grabbing" />304 </div>305 )}306 {showClose && (307 <div308 className={cn(309 'flex justify-end px-4 pt-2 pb-0',310 isVertical && 'mx-auto w-full max-w-lg',311 )}312 >313 <motion.button314 type="button"315 whileTap={shouldReduceMotion ? undefined : CLOSE_BUTTON_TAP}316 onClick={() => setOpen(false)}317 className="hover:bg-muted focus-visible:ring-ring rounded-full p-2 transition-colors focus-visible:ring-2 focus-visible:outline-none"318 aria-label={closeLabel}319 >320 <XIcon className="h-4 w-4" size={16} />321 </motion.button>322 </div>323 )}324 </div>325 <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">326 <div className={cn('px-5 pt-2 pb-5', isVertical && 'mx-auto w-full max-w-lg')}>327 {children}328 </div>329 </div>330 </motion.div>331 </>332 )}333 </AnimatePresence>334 );335336 return createPortal(drawer, document.body);337};338339const DrawerClose = ({340 children,341 onClick,342 ...props343}: React.ButtonHTMLAttributes<HTMLButtonElement>) => {344 const { setOpen } = useDrawerContext();345346 return (347 <button348 type="button"349 onClick={(e) => {350 onClick?.(e);351 setOpen(false);352 }}353 {...props}354 >355 {children}356 </button>357 );358};359360const DrawerHeader = ({361 children,362 className,363}: {364 children: React.ReactNode;365 className?: string;366}) => {367 return <div className={cn('mb-4', className)}>{children}</div>;368};369370const DrawerTitle = ({371 children,372 className,373}: {374 children: React.ReactNode;375 className?: string;376}) => {377 const { id, setHasTitle } = useDrawerContext();378379 React.useEffect(() => {380 setHasTitle(true);381 return () => setHasTitle(false);382 }, [setHasTitle]);383384 return (385 <h2 id={`${id}-title`} className={cn('text-xl font-semibold tracking-tight', className)}>386 {children}387 </h2>388 );389};390391const DrawerDescription = ({392 children,393 className,394}: {395 children: React.ReactNode;396 className?: string;397}) => {398 const { id, setHasDescription } = useDrawerContext();399400 React.useEffect(() => {401 setHasDescription(true);402 return () => setHasDescription(false);403 }, [setHasDescription]);404405 return (406 <p id={`${id}-description`} className={cn('text-muted-foreground mt-1 text-sm', className)}>407 {children}408 </p>409 );410};411412const Drawer = Object.assign(DrawerRoot, {413 Trigger: DrawerTrigger,414 Content: DrawerContent,415 Header: DrawerHeader,416 Title: DrawerTitle,417 Description: DrawerDescription,418 Close: DrawerClose,419});420421export { Drawer };
Actualiza las rutas de importación para que coincidan con la estructura de tu proyecto.
Anatomía
1import { Drawer } from '@/components/drawer';
1<Drawer>2 <Drawer.Trigger>3 <Button>Abrir Drawer</Button>4 </Drawer.Trigger>5 <Drawer.Content>6 <Drawer.Header>7 <Drawer.Title>Título del Drawer</Drawer.Title>8 <Drawer.Description>Este es un componente drawer.</Drawer.Description>9 </Drawer.Header>10 <div>Tu contenido aquí</div>11 </Drawer.Content>12</Drawer>
Composición
Usa la siguiente composición para construir un
Drawer:Drawer├── Drawer.Trigger└── Drawer.Content└── Drawer.Header├── Drawer.Title└── Drawer.Description
Características
- Múltiples lados - Desliza desde abajo, arriba, izquierda o derecha
- Arrastrar para cerrar - Desliza para descartar en cualquier dirección
- Responsivo - Se adapta a diferentes tamaños de pantalla
- Animaciones suaves - Transiciones de deslizamiento basadas en resorte
- Trampa de foco - La navegación por teclado se mantiene dentro del drawer
- Bloqueo de scroll - Evita el desplazamiento del fondo cuando está abierto
Variantes
Posiciones (Positions)
1'use client';23import { Drawer } from '@/components/drawer';45const panels = [6 {7 side: 'top',8 trigger: 'Release notes',9 title: 'What changed in v2.14',10 description: 'Shipped to production on Mar 14.',11 items: [12 'Deploy logs now stream while the build runs',13 'Region picker moved into project settings',14 'Fixed stale cache on custom domains',15 ],16 action: 'Got it',17 },18 {19 side: 'right',20 trigger: 'Filters',21 title: 'Filter deploys',22 description: '1,204 deploys in this project.',23 items: ['Production only', 'Failed builds', 'Last 7 days'],24 action: 'Apply filters',25 },26 {27 side: 'bottom',28 trigger: 'Quick actions',29 title: 'Run a task',30 description: 'Nothing here leaves the dashboard.',31 items: ['Redeploy the latest commit', 'Roll back to v2.13.4', 'Clear the build cache'],32 action: 'Close',33 },34 {35 side: 'left',36 trigger: 'Workspace',37 title: 'Northwind',38 description: 'Pro plan, 12 of 20 seats used.',39 items: ['Projects', 'Deployments', 'Usage and billing'],40 action: 'Close',41 },42] as const;4344export function Positions() {45 return (46 <div className="grid w-full max-w-md grid-cols-2 gap-4">47 {panels.map((panel) => (48 <Drawer key={panel.side}>49 <Drawer.Trigger variant="outline" className="w-full justify-between gap-2">50 {panel.trigger}51 <span className="text-muted-foreground text-xs">{panel.side}</span>52 </Drawer.Trigger>53 <Drawer.Content side={panel.side}>54 <Drawer.Header>55 <Drawer.Title>{panel.title}</Drawer.Title>56 <Drawer.Description>{panel.description}</Drawer.Description>57 </Drawer.Header>58 <ul className="text-muted-foreground flex flex-col gap-2 text-sm">59 {panel.items.map((item) => (60 <li key={item} className="bg-card rounded-md px-3 py-2 shadow-sm">61 {item}62 </li>63 ))}64 </ul>65 <div className="mt-6 flex justify-end">66 <Drawer.Close className="text-muted-foreground hover:text-foreground text-sm transition-colors">67 {panel.action}68 </Drawer.Close>69 </div>70 </Drawer.Content>71 </Drawer>72 ))}73 </div>74 );75}
Formulario (Form)
1'use client';23import { Button } from '@/components/button';4import { Drawer } from '@/components/drawer';5import { Input } from '@/components/input';6import { Label } from '@/components/label';7import { Select } from '@/components/select';89export function Form() {10 return (11 <Drawer>12 <Drawer.Trigger variant="outline">New API key</Drawer.Trigger>13 <Drawer.Content side="bottom">14 <Drawer.Header>15 <Drawer.Title>Create an API key</Drawer.Title>16 <Drawer.Description>17 The secret is shown once, right after you create it. Store it in your CI provider before18 you close this panel.19 </Drawer.Description>20 </Drawer.Header>2122 <div className="mx-auto grid w-full max-w-md gap-4 py-2">23 <Input24 id="key-name"25 label="Key name"26 defaultValue="ci-deploy-prod"27 description="Shown in the audit log next to every request."28 />29 <div className="grid gap-4 sm:grid-cols-2">30 <div className="grid gap-1.5">31 <Label htmlFor="key-scope">Scope</Label>32 <Select defaultValue="deploy">33 <Select.Trigger id="key-scope" />34 <Select.Content>35 <Select.Item value="read">Read only</Select.Item>36 <Select.Item value="deploy">Deploy and read logs</Select.Item>37 <Select.Item value="admin">Full workspace access</Select.Item>38 </Select.Content>39 </Select>40 </div>41 <div className="grid gap-1.5">42 <Label htmlFor="key-expiry">Expires</Label>43 <Select defaultValue="90">44 <Select.Trigger id="key-expiry" />45 <Select.Content>46 <Select.Item value="30">In 30 days</Select.Item>47 <Select.Item value="90">In 90 days</Select.Item>48 <Select.Item value="never">Never</Select.Item>49 </Select.Content>50 </Select>51 </div>52 </div>53 </div>5455 <div className="mx-auto flex w-full max-w-md items-center justify-end gap-2">56 <Drawer.Close className="text-muted-foreground hover:text-foreground text-sm transition-colors">57 Cancel58 </Drawer.Close>59 <Button size="sm">Create key</Button>60 </div>61 </Drawer.Content>62 </Drawer>63 );64}
Referencia de API
Drawer
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
children | ReactNode | - | Activador y contenido del drawer |
defaultOpen | boolean | false | Estado abierto inicial |
open | boolean | - | Estado abierto controlado |
onOpenChange | (open: boolean) => void | - | Callback cuando cambia el estado |
Drawer.Trigger
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
children | ReactNode | - | Contenido del botón activador |
className | string | - | Clases CSS adicionales |
variant | ButtonProps['variant'] | - | Variante del botón |
size | ButtonProps['size'] | - | Tamaño del botón |
Drawer.Content
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
side | 'bottom' | 'top' | 'left' | 'right' | 'bottom' | Lado desde el que deslizar |
showDragHandle | boolean | true | Mostrar asa de arrastre para cerrar |
showClose | boolean | true | Muestra el botón de cierre |
closeLabel | string | 'Close' | Nombre accesible del botón de cierre |
className | string | - | Clases CSS adicionales |
Drawer.Header
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
className | string | - | Clases CSS adicionales |
Drawer.Title
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
className | string | - | Clases CSS adicionales |
Drawer.Description
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
className | string | - | Clases CSS adicionales |
Drawer.Close
| Prop | Tipo | Por defecto | Descripción |
|---|---|---|---|
children | ReactNode | - | Contenido clicable |
¿Encontraste algo que mejorar?
¿Notaste un error, tipografía o detalle faltante en esta página? Ayúdanos a mejorar la documentación abriendo un issue en GitHub.