Skip to content

Alert Dialog

Interrupts the user with an action that needs a decision before work can continue.

Installation

pnpm dlx shadcn@latest add @silkware/alert-dialog

To copy the component by hand, install its dependencies:

pnpm add react-aria-components cn

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

components/ui/alert-dialog.tsx
"use client"
import * as React from "react"import { cn } from "cn"import {  Dialog as AlertDialogPrimitive,  DialogTrigger as AlertDialogTriggerPrimitive,  Heading,  ModalOverlay as ModalOverlayPrimitive,  Modal as ModalPrimitive,  type DialogProps as AlertDialogPrimitiveProps,  type DialogTriggerProps as AlertDialogTriggerPrimitiveProps,  type ModalOverlayProps as ModalOverlayPrimitiveProps,} from "@animate-ui/react/primitives/react-aria"
import { Button } from "@/components/ui/button"
function AlertDialogTrigger({ ...props }: AlertDialogTriggerPrimitiveProps) {  return (    <AlertDialogTriggerPrimitive data-slot="alert-dialog-trigger" {...props} />  )}
function AlertDialogOverlay({  className,  children,  ...props}: Omit<ModalOverlayPrimitiveProps, "className" | "children"> & {  className?: string  children: React.ReactNode}) {  return (    <ModalOverlayPrimitive      data-slot="alert-dialog-overlay"      className={cn(        "fixed inset-0 isolate z-50 bg-black/10 supports-backdrop-filter:backdrop-blur-xs",        className      )}      {...props}    >      {children}    </ModalOverlayPrimitive>  )}
function AlertDialog({  className,  size = "default",  children,  ...props}: Omit<ModalOverlayPrimitiveProps, "className" | "children"> &  Pick<React.ComponentProps<typeof ModalPrimitive>, "isDismissable"> & {    className?: string    size?: "default" | "sm"    children: React.ReactNode  }) {  return (    <AlertDialogOverlay {...props}>      <ModalPrimitive        data-slot="alert-dialog-content"        data-size={size}        className={cn(          "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-popover-foreground ring-1 ring-foreground/10 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg",          className        )}      >        <AlertDialogPrimitive          data-slot="alert-dialog"          role="alertdialog"          className="[display:inherit] [gap:inherit] outline-none"        >          {children}        </AlertDialogPrimitive>      </ModalPrimitive>    </AlertDialogOverlay>  )}
function AlertDialogContent({  className,  size = "default",  children,  ...props}: React.ComponentProps<typeof AlertDialog>) {  return (    <AlertDialog className={className} size={size} {...props}>      {children}    </AlertDialog>  )}
function AlertDialogHeader({  className,  ...props}: React.ComponentProps<"div">) {  return (    <div      data-slot="alert-dialog-header"      className={cn(        "grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",        className      )}      {...props}    />  )}
function AlertDialogFooter({  className,  ...props}: React.ComponentProps<"div">) {  return (    <div      data-slot="alert-dialog-footer"      className={cn(        "flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",        className      )}      {...props}    />  )}
function AlertDialogMedia({  className,  ...props}: React.ComponentProps<"div">) {  return (    <div      data-slot="alert-dialog-media"      className={cn(        "mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",        className      )}      {...props}    />  )}
function AlertDialogTitle({  className,  ...props}: Omit<React.ComponentProps<typeof Heading>, "slot">) {  return (    <Heading      slot="title"      data-slot="alert-dialog-title"      className={cn(        "font-heading text-lg font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",        className      )}      {...props}    />  )}
function AlertDialogDescription({  className,  ...props}: Omit<React.ComponentProps<"div">, "slot">) {  return (    <div      data-slot="alert-dialog-description"      className={cn(        "text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",        className      )}      {...props}    />  )}
function AlertDialogAction({  className,  ...props}: React.ComponentProps<typeof Button>) {  return (    <Button      slot="close"      data-slot="alert-dialog-action"      className={cn(className)}      {...props}    />  )}
function AlertDialogCancel({  className,  variant = "outline",  size = "default",  ...props}: React.ComponentProps<typeof Button>) {  return (    <Button      slot="close"      data-slot="alert-dialog-cancel"      className={cn(className)}      variant={variant}      size={size}      {...props}    />  )}
export {  AlertDialog,  AlertDialogAction,  AlertDialogCancel,  AlertDialogContent,  AlertDialogDescription,  AlertDialogFooter,  AlertDialogHeader,  AlertDialogMedia,  AlertDialogOverlay,  AlertDialogTitle,  AlertDialogTrigger,}

Usage

import { Button } from "@/components/ui/button"import {  AlertDialog,  AlertDialogAction,  AlertDialogCancel,  AlertDialogDescription,  AlertDialogFooter,  AlertDialogHeader,  AlertDialogTitle,  AlertDialogTrigger,} from "@/components/ui/alert-dialog"
<AlertDialogTrigger>  <Button variant="destructive">Delete supplier</Button>  <AlertDialog>    <AlertDialogHeader>      <AlertDialogTitle>Delete Tornival?</AlertDialogTitle>      <AlertDialogDescription>        The supplier and its price agreements are removed for everyone.      </AlertDialogDescription>    </AlertDialogHeader>    <AlertDialogFooter>      <AlertDialogCancel>Keep supplier</AlertDialogCancel>      <AlertDialogAction variant="destructive">Delete supplier</AlertDialogAction>    </AlertDialogFooter>  </AlertDialog></AlertDialogTrigger>

AlertDialogAction renders a default button, so a destructive action needs variant="destructive". Both the action and the cancel button close the dialog. Run your work in the action's onPress.

Examples

Destructive

Removing data or ending something for other people. The trigger, the action and the title use the same verb, and the cancel button says what is kept. The first example on this page puts autoFocus on the cancel button, so focus starts on the safe choice.

Confirm

An action that is easy to regret but does not destroy data, such as sending an order. Keep the default button style for the action.

Small

size="sm" narrows the dialog and lays the two buttons out as equal columns, also on larger screens. Use it for a short question.

With media

AlertDialogMedia puts an icon beside the title. On a destructive dialog, tint it with the destructive colours.

Small with media

The icon sits above the text in the small size.

Controlled

Pass isOpen and onOpenChange to AlertDialogTrigger to own the open state, and run the work in onPress on the action.

Order status: Open

Accessibility

KeyAction
TabMoves focus to the next button. From the last button it returns to the first.
ShiftTabMoves focus to the previous button.
EscCloses the dialog without running the action, and returns focus to the trigger.
SpacePresses the focused button.
EnterPresses the focused button.

React Aria provides:

  • The alertdialog role, set by this component, so screen readers announce the dialog as one that needs a response.
  • A name from the AlertDialogTitle, and focus that moves into the dialog, stays there and returns to the trigger on close.
  • Content outside the dialog hidden from assistive technology while it is open.
  • A click outside that does not close the dialog by default. This differs from Dialog, where it does. Pass isDismissable to allow it.

You provide:

  • A title that states the decision as a question, and a description that states the consequence.
  • Button labels that name the outcomes, not "Yes" and "No".
  • autoFocus on the cancel button when the action destroys data, so that a stray Enter keeps the data.

Guidelines

When to use

  • Before an action that removes data or cannot be undone: deleting a supplier, cancelling an order, discarding a draft.
  • Before an action that affects other people and is hard to take back, such as sending an order to a supplier.

When not to use

  • For a task with fields. Use a Dialog, or a Sheet for a longer one.
  • For an action the user can undo. Carry it out and offer Undo in a toast. Confirmation fatigue teaches people to click through.
  • To tell the user something that needs no decision. Put the message on the page, or use a toast.
  • To report an error in a form. Show it next to the field.

Content

  • Title: the question, with the object in it. "Delete Tornival?" says what is at stake; "Are you sure?" does not.
  • Description: what is lost or sent, and who it affects, in one or two sentences. Say "This cannot be undone" only when it is true.
  • Buttons: the cancel button says what is kept ("Keep supplier"), the action repeats the verb of the trigger ("Delete supplier"). The action goes last.
  • Use the destructive variant for the action only when data is removed.

Hierarchy

Open an alert dialog from a control the user chose on purpose. The trigger does not need to be destructive itself, but its label and the action label must name the same thing.

Do

Name the object and the consequence, and give the buttons verbs.

Don’t

Don’t ask "Are you sure?" with a generic warning and "Yes" or "No" buttons.

Order PO-2041 archived.

Do

Carry out an action that can be undone and offer Undo.

Don’t

Don’t confirm an action the user can take back. Archiving an order does not need a dialog.

API reference

AlertDialogTrigger

Wraps the trigger and the dialog through the React Aria DialogTrigger. It accepts every DialogTrigger prop.

PropTypeDefaultDescription
childrenReactNodeNoneA pressable trigger, then the AlertDialog.
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.

AlertDialog and AlertDialogContent

Renders the overlay, modal and dialog with role="alertdialog". It accepts every React Aria ModalOverlay prop and the props below. AlertDialogContent is an alias with the same props.

PropTypeDefaultDescription
size?"default" | "sm""default"The width of the dialog. The small size lays the footer out as two equal columns.
isDismissable?booleanfalseCloses the dialog on an interaction outside it.
isKeyboardDismissDisabled?booleanfalseStops Escape from closing the dialog.
className?stringNoneClasses merged onto the dialog window.
childrenReactNodeNoneThe dialog content.

AlertDialogHeader

A div that lays out the optional media, the title and the description. It accepts every div prop.

AlertDialogMedia

A div that holds an icon or an image, in a muted square. It accepts every div prop.

AlertDialogTitle

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

AlertDialogDescription

A div with muted text. It accepts every div prop except slot.

AlertDialogFooter

A div that holds the actions. It stacks them on a phone and sets them in a row from the sm breakpoint. It accepts every div prop.

AlertDialogAction

Renders a Button with slot="close". Pressing it runs onPress and closes the dialog. It accepts every Button prop, with the default variant.

AlertDialogCancel

Renders a Button with slot="close" and the outline variant. 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.

AlertDialogOverlay

The dimmed layer behind the dialog, through the React Aria ModalOverlay. AlertDialog renders it for you.