Skip to content

Dialog

Opens a window over the page for a task or a piece of information that needs focus before the user goes back to the page.

Installation

pnpm dlx shadcn@latest add @silkware/dialog

To copy the component by hand, install its dependencies:

pnpm add react-aria-components cn lucide-react

Then copy the source into components/ui/dialog.tsx. It uses the Button component, so add that first.

components/ui/dialog.tsx
"use client"
import * as React from "react"import { cn } from "cn"import {  Dialog as DialogPrimitive,  DialogTrigger as DialogTriggerPrimitive,  Heading,  ModalOverlay as ModalOverlayPrimitive,  Modal as ModalPrimitive,  type DialogProps as DialogPrimitiveProps,  type DialogTriggerProps as DialogTriggerPrimitiveProps,  type ModalOverlayProps as ModalOverlayPrimitiveProps,} from "@animate-ui/react/primitives/react-aria"
import { Button } from "@/components/ui/button"import { XIcon } from "lucide-react"
function DialogTrigger({ ...props }: DialogTriggerPrimitiveProps) {  return <DialogTriggerPrimitive data-slot="dialog-trigger" {...props} />}
function DialogClose({  className,  variant = "outline",  size = "default",  ...props}: React.ComponentProps<typeof Button>) {  return (    <Button      slot="close"      data-slot="dialog-close"      variant={variant}      size={size}      className={cn(className)}      {...props}    />  )}
function DialogOverlay({  className,  children,  ...props}: Omit<ModalOverlayPrimitiveProps, "className" | "children"> & {  className?: string  children: React.ReactNode}) {  return (    <ModalOverlayPrimitive      data-slot="dialog-overlay"      className={cn(        "fixed inset-0 isolate z-50 bg-black/10 supports-backdrop-filter:backdrop-blur-xs",        className      )}      {...props}    >      {children}    </ModalOverlayPrimitive>  )}
function Dialog({  className,  children,  showCloseButton = true,  isDismissable = true,  ...props}: Omit<ModalOverlayPrimitiveProps, "className" | "children"> &  Pick<React.ComponentProps<typeof ModalPrimitive>, "isDismissable"> & {    className?: string    children: React.ReactNode    showCloseButton?: boolean  }) {  return (    <DialogOverlay isDismissable={isDismissable} {...props}>      <ModalPrimitive        data-slot="dialog-content"        className={cn(          "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-sm text-popover-foreground ring-1 ring-foreground/10 outline-none sm:max-w-md",          className        )}      >        <DialogPrimitive          data-slot="dialog"          className="[display:inherit] [gap:inherit] outline-none"        >          {children}          {showCloseButton && (            <DialogClose              variant="ghost"              className="absolute top-4 right-4"              size="icon-sm"            >              <XIcon              />              <span className="sr-only">Close</span>            </DialogClose>          )}        </DialogPrimitive>      </ModalPrimitive>    </DialogOverlay>  )}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="dialog-header"      className={cn("flex flex-col gap-2", className)}      {...props}    />  )}
function DialogFooter({  className,  showCloseButton = false,  children,  ...props}: React.ComponentProps<"div"> & {  showCloseButton?: boolean}) {  return (    <div      data-slot="dialog-footer"      className={cn(        "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",        className      )}      {...props}    >      {children}      {showCloseButton && <DialogClose variant="outline">Close</DialogClose>}    </div>  )}
function DialogTitle({  className,  ...props}: Omit<React.ComponentProps<typeof Heading>, "slot">) {  return (    <Heading      slot="title"      data-slot="dialog-title"      className={cn("font-heading leading-none font-medium", className)}      {...props}    />  )}
function DialogDescription({  className,  ...props}: Omit<React.ComponentProps<"div">, "slot">) {  return (    <div      data-slot="dialog-description"      className={cn(        "text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",        className      )}      {...props}    />  )}
export {  type DialogPrimitiveProps,  type DialogTriggerPrimitiveProps,  Dialog,  DialogClose,  DialogDescription,  DialogFooter,  DialogHeader,  DialogOverlay,  DialogTitle,  DialogTrigger,}

Usage

import { Button } from "@/components/ui/button"import {  Dialog,  DialogClose,  DialogDescription,  DialogFooter,  DialogHeader,  DialogTitle,  DialogTrigger,} from "@/components/ui/dialog"
<DialogTrigger>  <Button variant="outline">Edit supplier</Button>  <Dialog>    <DialogHeader>      <DialogTitle>Edit supplier</DialogTitle>      <DialogDescription>Update the contact details.</DialogDescription>    </DialogHeader>    <DialogFooter>      <DialogClose>Cancel</DialogClose>    </DialogFooter>  </Dialog></DialogTrigger>

DialogTrigger takes exactly two children: the pressable trigger first, then the Dialog. Components in this set that close the dialog, DialogClose and the close button, do so through slot="close", so they must sit inside the Dialog. To run your own code when a button is pressed and close the dialog, use controlled state, shown below.

Examples

Form

Collect a few fields without leaving the page. Control the open state, so that submitting the form can close the dialog once the data is saved. Give the first field autoFocus so focus lands where the user starts typing.

Controlled

Pass isOpen and onOpenChange to DialogTrigger to open and close the dialog from your own code, for example after a request finishes. Close it from a button with onPress.

Status: Waiting for approval

Scrollable content

A dialog never grows past the screen. Put long content in a region with a maximum height and overflow-y-auto, so that the title and the actions stay in view.

Without the close button

showCloseButton={false} removes the cross in the corner. Use it when the footer already has a clear way out. The user can still press Escape or click outside the dialog.

Not dismissable

A click outside the dialog closes it by default. Set isDismissable={false} to keep it open, and isKeyboardDismissDisabled to make Escape do nothing as well. Do this only when the user must choose an action, and then consider an Alert Dialog.

Accessibility

KeyAction
TabMoves focus to the next control inside the dialog. From the last control it returns to the first.
ShiftTabMoves focus to the previous control inside the dialog.
EscCloses the dialog and returns focus to the trigger, unless isKeyboardDismissDisabled is set.
SpacePresses the focused button, including the trigger and the close button.
EnterPresses the focused button, including the trigger and the close button.

React Aria provides:

  • The dialog role on the window, labelled by the DialogTitle through the title slot.
  • Focus that moves into the dialog when it opens, stays inside while it is open and returns to the trigger when it closes.
  • Content outside the dialog hidden from screen readers and from the keyboard while the dialog is open, and page scrolling prevented.
  • Closing on Escape and on an interaction outside the dialog, with the props above to turn either off.
  • The data-entering and data-exiting states that drive the enter and exit animation.

You provide:

  • A DialogTitle in every dialog. Without it the dialog has no accessible name.
  • A DialogDescription that says what the dialog is for, when the title is not enough.
  • A label on every control inside the dialog, and an aria-label on a trigger that holds only an icon.
  • A way to leave: the close button, a Cancel button, or both.

Guidelines

When to use

  • To complete a short task that needs the user's full attention, such as editing a supplier or adding a note to an order.
  • To show a detail that the user asked for and must read before going on, such as delivery terms.
  • To ask for a few fields that belong to the page the user is on.

When not to use

  • To ask for confirmation of an action that cannot be undone. Use an Alert Dialog, which announces itself as an alert and does not close on an outside click.
  • For a longer form or a panel the user may keep open while they look at the page. Use a Sheet.
  • For a touch-first panel that the user swipes away on a phone. Use a Drawer.
  • For a small control or a few fields next to the element that opens them. Use a Popover.
  • For a message that needs no decision. Use a toast, or put the message on the page.
  • To explain an icon or a button. Use a Tooltip.

Content

  • Write the title as the task, in sentence case with no full stop: "Edit supplier", "Add note".
  • Use the description for one or two sentences that say what changes, not to repeat the title.
  • Name the buttons after what they do: "Save supplier", "Move delivery". Put the main action last.
  • Keep the dialog to one task. If it needs steps or tabs, it is a page.

Focus and dismissal

A dialog opens above everything and takes focus, so the user must always be able to get out. Keep Escape and the outside click working unless closing would lose work or skip a required choice. When the dialog holds a form with unsaved input, confirm before you throw the input away.

Actions

Do

Title the dialog after the task and name each button after its outcome.

Don’t

Don’t ask "Are you sure?" and answer with "Yes" and "No". The user has to guess what each one does.

API reference

DialogTrigger

Wraps the trigger and the dialog, and ties them together through the React Aria DialogTrigger. It accepts every React Aria DialogTrigger prop.

PropTypeDefaultDescription
childrenReactNodeNoneA pressable trigger, then the Dialog.
isOpen?booleanNoneWhether the dialog is open. Makes the dialog controlled.
defaultOpen?booleanNoneWhether the dialog is open on first render, when uncontrolled.
onOpenChange?(isOpen: boolean) => voidNoneCalled when the dialog opens or closes.

Dialog

Renders the overlay, the modal and the dialog through the React Aria ModalOverlay, Modal and Dialog. It accepts every ModalOverlay prop and the props below.

PropTypeDefaultDescription
showCloseButton?booleantrueShows the close button in the top right corner.
isDismissable?booleantrueCloses the dialog on an interaction outside it.
isKeyboardDismissDisabled?booleanfalseStops Escape from closing the dialog.
isOpen?booleanNoneWhether the dialog is open, when you use Dialog without DialogTrigger.
onOpenChange?(isOpen: boolean) => voidNoneCalled when the dialog opens or closes.
className?stringNoneClasses merged onto the dialog window. Use it to set the width, for example sm:max-w-lg.
childrenReactNodeNoneThe dialog content.

DialogHeader

A div that stacks the title and the description. It accepts every div prop.

DialogTitle

Renders a heading through the React Aria Heading with slot="title", which labels the dialog. It accepts every Heading prop except slot.

DialogDescription

A div with muted text. It accepts every div prop except slot. Links inside it are underlined.

DialogFooter

A div that holds the actions. It stacks them on a phone, with the main action on top, and puts them in a row, aligned to the end, from the sm breakpoint.

PropTypeDefaultDescription
showCloseButton?booleanfalseAdds an outline Close button that closes the dialog.

DialogClose

Renders a Button with slot="close", so pressing it closes the dialog. It accepts every Button prop.

PropTypeDefaultDescription
variant?"default" | "secondary" | "outline" | "ghost" | "destructive" | "link""outline"The visual weight of the button.
size?"xs" | "sm" | "default" | "lg" | "icon-xs" | "icon-sm" | "icon" | "icon-lg""default"The height and padding.

DialogOverlay

The dimmed layer behind the dialog, through the React Aria ModalOverlay. Dialog renders it for you. Use it only to compose a dialog by hand.