Capítulo 10 de 43

Chapter 10: Alert Dialog

Core Idea

A modal dialog that interrupts the user and demands a response — distinct from Dialog in that it auto-traps focus, auto-closes on Escape, and requires distinguishable Cancel/Action buttons for a destructive-confirmation-style UX.

Key Concepts

  • Anatomy: RootTrigger, PortalOverlay, ContentTitle, Description, Cancel, Action.
  • Title/Description: announced to screen readers on open; can be replaced by aria-label/aria-describedby on Content if you omit them.
  • Cancel vs Action: both close the dialog, but must be styled distinctly — Cancel is the safe/dismiss path, Action is the confirming/destructive path.
  • Controlled open/onOpenChange: needed for patterns like closing after an async operation completes.

Code Examples

const [open, setOpen] = React.useState(false);

<AlertDialog.Root open={open} onOpenChange={setOpen}>
  <AlertDialog.Trigger>Open</AlertDialog.Trigger>
  <AlertDialog.Portal>
    <AlertDialog.Overlay />
    <AlertDialog.Content>
      <form onSubmit={(e) => { wait().then(() => setOpen(false)); e.preventDefault(); }}>
        <button type="submit">Submit</button>
      </form>
    </AlertDialog.Content>
  </AlertDialog.Portal>
</AlertDialog.Root>
  • What it demonstrates: closing the dialog programmatically after an async form submission completes, via controlled state.

Reference Tables

PartKey props
RootdefaultOpen, open, onOpenChange
Portalcontainer (default document.body), forceMount
ContentonOpenAutoFocus, onCloseAutoFocus, onEscapeKeyDown

Anti-patterns

  • Using Dialog instead of AlertDialog for destructive confirmations: Dialog doesn't guarantee the same auto-focus-trap/Escape/announcement behavior expected for an interrupting prompt.
  • Styling Cancel and Action identically: defeats the accessibility/UX purpose of the pattern — users must be able to tell the safe option from the destructive one at a glance.

Key Takeaways

  1. Reach for AlertDialog specifically when the user must respond before continuing (e.g. "Delete this item?") — not for general-purpose modals.
  2. Focus is automatically trapped and moved to Cancel on open — no manual focus management needed.
  3. Portal's container prop lets you render into something other than document.body (e.g. a shadow-DOM root or a specific app container).

Connects To

  • Dialog: the general-purpose modal this component specializes.
  • Accessibility: the auto-focus-to-Cancel behavior cited there as an example.