An alert dialog interrupts the user with a question that needs an answer: "Delete this project?". It is a Dialog with three things fixed: the alertdialog role, no light dismiss (a stray click on the backdrop does nothing), and the initial focus on AlertDialog.Cancel, the answer that destroys nothing. AlertDialog.Action is the asynchronous half: it runs your action in its own transition, shows data-pending on itself, closes the dialog when the action resolves and leaves it open when it rejects.
"use client";
import { startTransition, useState } from "react";
import { AlertDialog } from "@funstack/ui/alert-dialog";
import { fakeSave } from "./fake-api.js";
// The confirmed work is the Action's `action`: it runs in the Delete button's own transition
// (data-pending, "Deleting…"), and the dialog closes only when it resolves. With "Make the
// server fail" checked the save fails: the action catches the error, shows it in the dialog and
// calls `details.reject()`, so the dialog stays open with Cancel and Delete usable (Delete is
// then a retry; Escape still leaves). The dialog opens with focus on Cancel, the answer that
// destroys nothing, and a click on the backdrop does nothing.
export function AlertDialogDeleteProject() {
const [deleted, setDeleted] = useState(false);
const [fail, setFail] = useState(false);
const [failure, setFailure] = useState<string | null>(null);
if (deleted) {
return (
<div className="demo-row">
<output className="demo-readout">Project "Atlas" deleted.</output>
{/* The dialog and its Trigger are gone: put focus on the next thing to do. */}
<button type="button" className="demo-button" autoFocus onClick={() => setDeleted(false)}>
Restore
</button>
</div>
);
}
return (
<div className="demo-row">
<AlertDialog.Root defaultOpen={false}>
<AlertDialog.Trigger className="demo-button demo-danger">
Delete project…
</AlertDialog.Trigger>
<AlertDialog.Popup className="demo-dialog">
<AlertDialog.Title>Delete "Atlas"?</AlertDialog.Title>
<AlertDialog.Description>
The project and its 12 documents are removed for everyone. This cannot be undone.
</AlertDialog.Description>
{failure !== null && (
<p className="demo-inline-error" role="alert">
{failure}
</p>
)}
<div className="demo-dialog-actions">
{/* Clicked while Delete runs, it shows data-pending until the dialog closes. */}
<AlertDialog.Cancel className="demo-button demo-cancel">Cancel</AlertDialog.Cancel>
<AlertDialog.Action
className="demo-button demo-danger"
action={async (details) => {
setFailure(null);
try {
await fakeSave('"Atlas"', { ms: 1000, fail });
} catch (e) {
// After an await: wrap the update yourself (React limitation).
startTransition(() => setFailure(e instanceof Error ? e.message : String(e)));
details.reject(); // the dialog stays open; no Error Boundary
return;
}
startTransition(() => setDeleted(true));
}}
>
{({ pending }) => (
<>
{pending && <span className="demo-spinner" aria-hidden />}
{pending ? "Deleting…" : "Delete"}
</>
)}
</AlertDialog.Action>
</div>
</AlertDialog.Popup>
</AlertDialog.Root>
<label className="demo-label">
<input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} /> Make
the server fail
</label>
</div>
);
}/* Dialog: the Popup is the <dialog> itself. Open state is `:open` / `:modal` on it (exact in
both modes); the Trigger carries `data-open` / `data-pending` in library mode only. */
/* CSS-only scroll lock, keyed on :modal: covers dialogs opened before hydration and nested ones. */
html:has(.demo-dialog:modal) {
overflow: hidden;
}
.demo-dialog {
inline-size: min(28rem, calc(100vw - 32px));
padding: 20px 24px;
border: 1px solid var(--color-border);
border-radius: 10px;
background: var(--color-bg);
color: var(--color-text);
box-shadow: 0 12px 40px rgb(0 0 0 / 0.3);
overscroll-behavior: contain;
}
.demo-dialog::backdrop {
background: rgb(0 0 0 / 0.45);
}
.demo-dialog h2 {
margin: 0 0 8px;
padding: 0;
border: 0;
font-size: 1.2rem;
}
.demo-dialog p {
margin: 0 0 12px;
color: var(--color-text-secondary);
}
/* Enter and exit with CSS, both modes. Enter works everywhere; the exit animates in Chromium
(with `overlay`) and Safari and is instant in Firefox. */
.demo-dialog,
.demo-dialog::backdrop {
opacity: 0;
transition:
opacity 150ms,
translate 150ms,
display 150ms allow-discrete,
overlay 150ms allow-discrete;
}
.demo-dialog {
translate: 0 8px;
}
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 1;
translate: 0 0;
}
@starting-style {
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 0;
}
.demo-dialog:open {
translate: 0 8px;
}
}
/* With `transition`, a view transition animates the library-driven opens and closes (a Close
part, a Form, a controlled close), Firefox included; dismissals (Escape, a click on the
backdrop) are the browser's and keep the CSS exit above.
The library keeps the two apart; no extra rule is needed. */
::view-transition-new(.demo-dialog-pop) {
animation: 180ms ease-out both demo-dialog-pop-in;
}
::view-transition-old(.demo-dialog-pop) {
animation: 140ms ease-in both demo-dialog-pop-out;
}
@keyframes demo-dialog-pop-in {
from {
opacity: 0;
scale: 0.96;
}
}
@keyframes demo-dialog-pop-out {
to {
opacity: 0;
scale: 0.96;
}
}
@media (prefers-reduced-motion: reduce) {
.demo-dialog,
.demo-dialog::backdrop {
transition: none;
}
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}
.demo-dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
.demo-dialog-form label {
display: grid;
gap: 4px;
}
.demo-dialog-form input {
padding: 0.35em 0.6em;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-bg);
color: var(--color-text);
font: inherit;
}
.demo-dialog-details {
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 16px;
margin: 0;
}
.demo-dialog-details dd {
margin: 0;
}
/* The Trigger in library mode: optimistic open and pending. */
.demo-button[data-open] {
border-color: var(--color-primary);
color: var(--color-primary);
}
.demo-button[data-pending] {
cursor: progress;
}
/* A Cancel clicked while the confirm runs: pending until its close commits (the close waits for
the confirm). The delay keeps a close that commits at once from flashing. */
.demo-cancel[data-pending] {
opacity: 0.6;
transition: opacity 0s 150ms;
}
ul.demo-list {
margin: 0 0 12px;
padding: 0;
list-style: none;
}
ul.demo-list .demo-row {
justify-content: space-between;
max-inline-size: 20rem;
padding-block: 4px;
}import { AlertDialog } from "@funstack/ui/alert-dialog";
<AlertDialog.Root> {/* no DOM: ids, mode, state */}
<AlertDialog.Trigger>Delete project</AlertDialog.Trigger>
<AlertDialog.Popup> {/* dialog[role=alertdialog] */}
<AlertDialog.Title>Delete "Atlas"?</AlertDialog.Title>
<AlertDialog.Description>This cannot be undone.</AlertDialog.Description>
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel> {/* focused on open */}
<AlertDialog.Action action={() => deleteProject(id)}>
Delete {/* pending, then closes */}
</AlertDialog.Action>
</AlertDialog.Popup>
</AlertDialog.Root>Dialog.Close's. Everything the Dialog page says applies unless this page says otherwise: the two modes, focus return, exit animations, keepMounted, transition, render.modal prop (always showModal()), no lightDismiss or experimental_closedBy, and role is owned. There is no Close part: it is Cancel.AlertDialog.Description (or an aria-describedby of yours) is a development warning (logged when its first showing ends), as a Popup without a Title is.| AlertDialog | |
|---|---|
| Role | role="alertdialog" on the <dialog>; aria-modal from showModal() |
| Backdrop click | Does nothing, in every engine and before hydration: a modal <dialog> without closedby does not light-dismiss |
| Escape, Android back | Closes the dialog: the browser's close request, a fact reported to onOpenChange(false, { reason: "dismiss", returnValue: "" }). It means "cancel"; there is no prop to turn it off |
| Initial focus | The first enabled AlertDialog.Cancel; initialFocus on the Popup overrides it; without a Cancel the platform chooses (the first focusable element) |
| Cancel | Dialog.Close under another name: a close request (reason: "activate", returnValue its value, "" by default) |
| Action | Dialog.Close under another name, usually with an action; with one it renders no commandfor / command (as every Close part), so a click before hydration does nothing |
| Modes | Dialog's: JS-free without open-state props on the Root, library mode with any |
The WAI-ARIA alert dialog pattern keeps Escape, as every modal dialog does, and keyboard and screen-reader users rely on it. The one mechanism that would block it, closedby="none", is missing in Safari and cannot be emulated there (the browser lets a page cancel a close request once per user activation, then closes anyway). So write the dialog so that a dismissal is a valid answer: Escape means Cancel, and the destructive step happens only in the Action's action. A dialog that must come back (an expired session) is controlled: a parent that keeps open after onOpenChange(false) gets it shown again at once.
Put it in the Action's action, not in openChangeAction. The action is where the pending state is on the button the user pressed, where a rejection keeps the dialog open, and where no dismissal can be mistaken for consent. An action that catches its own error resolves, and a resolved action closes the dialog. To keep the dialog open on a failure you handled, show the message and call details.reject() (as in the example above): nothing is dispatched, the dialog stays open with focus on the Action, and no Error Boundary is involved. Inside an alert dialog give the message role="alert", or move focus to it, so it is announced. For field errors use the Form with Form.Root.
With an Error Boundary instead (the action lets the error through), put the boundary around the Action only. A boundary that also wraps the Cancel replaces it with the fallback on failure, and Escape is then the only way out; one above the Root removes the dialog.
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<ErrorBoundary fallback={<span>Could not delete.</span>}>
<AlertDialog.Action action={() => deleteProject(id)}>Delete</AlertDialog.Action>
</ErrorBoundary>AlertDialog.Root| Prop | Type | Default | Description |
|---|---|---|---|
open | boolean | – | Controlled open state. undefined means uncontrolled. Selects library mode. Pass onOpenChange too: Escape closes the dialog without asking (development warns). |
defaultOpen | boolean | – | Initial open state in uncontrolled library mode. defaultOpen={false} selects library mode without an action. |
openChangeAction | ChangeAction<boolean, AlertDialogOpenChangeDetails> | – | Requests only: the Trigger (true), a Cancel, an Action, a Form submit or settle, a foreign close command (false, with details.returnValue the part's value). Awaited; the dialog opens or closes when it resolves; a controlled parent that keeps open vetoes a close. Never called for Escape. Runs in the Root's transition; may be a Server Function; rejections reach the nearest Error Boundary above the Root. Selects library mode. |
onOpenChange | UrgentChangeHandler<boolean, AlertDialogOpenChangeDetails> | – | Facts only: Escape, Android back, an assistive-technology dismiss, a script close() / requestClose(). Always false, with reason: "dismiss" and returnValue as the browser left it ("" for Escape). Called synchronously, outside any transition. In controlled mode set state directly here (onOpenChange={setOpen}). Selects library mode. On a controlled Root with no openChangeAction, also a part's close (Cancel, the Action after its action, a Form submission): the library performs it at once and calls this with "activate" (nothing waits). |
children | ReactNode | ((state: AlertDialogRootState) => ReactNode) | – | The parts. The function form receives the optimistic state and must not suspend. |
AlertDialogRootState is { open, pending, modal } (Dialog's; modal is always true).ref, className or style).There is no modal prop: an alert dialog is always modal.
AlertDialog.TriggerDialog.Trigger, unchanged: <button command="show-modal"> in JS-free mode, a request through the Root with data-open and data-pending in library mode. Props: disabled, className, style, children (functions of AlertDialogTriggerState, { open, pending, disabled }), render. In JS-free mode data-open follows the dialog; inside aToolbar.Root a disabled Trigger is aria-disabled and stays focusable. See Dialog.Trigger.
AlertDialog.Popup| Prop | Type | Default | Description |
|---|---|---|---|
initialFocus | RefObject<HTMLElement | null> | string | the first enabled Cancel | The element to focus on open: a ref, or a selector resolved inside the dialog. With it, no Cancel is focused. For a long message, point it at the Title with tabIndex={-1} so the text is read from the top. Without a Cancel and without initialFocus, the platform focuses the first focusable element. |
keepMounted | boolean | false | Library mode: keep the children in <Activity mode="hidden"> while closed instead of unmounting them. Ignored in JS-free mode (always mounted). |
transition | ViewTransitionClass | – | Library mode only. The class of the <ViewTransition> around the dialog; without it no boundary is rendered. A string animates this alert dialog's own open and its library-driven closes (Cancel, Action, Form) and its own mount and unmount (only as the top of what is inserted or removed), in all engines; nothing else (not another alert dialog, not an unrelated transition, not content that changes inside). A controlled open you change in your own transition needs a map keyed on fsui-dialog-open / fsui-dialog-close (Dialog's types) plus addTransitionType (recipe). A type map is React's: it names every alert dialog that has it and that a commit with its types reaches, and each plays the class; end it with default: "none" (Type maps). Dismissals animate with CSS only. A closed Popup renders its element one commit after its mount, before paint, so placing it (a row of a table that a Suspense boundary reveals) starts no view transition and its ref is still empty in the mount effects of the component that renders it (two-step mount). |
className | string | ((state: AlertDialogPopupState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: AlertDialogPopupState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: AlertDialogPopupState) => ReactNode) | – | Content, or a function of the part's state. |
render | ReactElement | ((props, state: AlertDialogPopupState) => ReactNode) | – | Replace the default <dialog> (element form) or take over rendering (function form). |
AlertDialogPopupState is { open, modal }; open is committed (false in JS-free mode; :open is the DOM truth).role (alertdialog), id, open, closedby (never rendered), data-modal, suppressHydrationWarning; aria-labelledby and aria-describedby name the Title and the Description only while each is mounted (none while the content is not rendered), merged with yours.onCancel and the other <dialog> props pass through.
AlertDialog.Cancel| Prop | Type | Default | Description |
|---|---|---|---|
value | string | "" | Becomes dialog.returnValue and details.returnValue of openChangeAction(false). The default is what Escape leaves, so both read as "nothing was confirmed". |
disabled | boolean | false | Native disabled; owned. A disabled Cancel is not the focus target: the next enabled one is. A click runs no onClick, a render element's included, and is cancelled; a render element's disabled disables the part too (unavailable parts). |
action | Action<[details: AlertDialogCancelActionDetails & Rejectable]> | – | Rarely needed. As on Dialog.Close: runs in this button's own transition, then closes the dialog; a rejection leaves it open. |
whilePending | "run" | "ignore" | "ignore" | As on Dialog.Close. No effect without action: the Cancel then shows data-pending while its close waits, never aria-disabled. |
className | string | ((state: AlertDialogCancelState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: AlertDialogCancelState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: AlertDialogCancelState) => ReactNode) | – | Content, or a function of the part's state. |
render | ReactElement | ((props, state: AlertDialogCancelState) => ReactNode) | – | Replace the default <button> (element form) or take over rendering (function form). |
AlertDialogCancelState is { pending, disabled }; pending runs from the click until the close it asked for has committed (library mode), for example while the close waits for a confirm that is still running.Dialog.Close's (type, disabled, aria-disabled, commandfor, command, value, onClick in library mode or with action, data-pending, data-disabled), and autoFocus in the server and hydration render while it is the focus target in JS-free mode (a Cancel mounted on the client into an open dialog carries the attribute but takes no focus).JS-free mode: <button command="request-close" autofocus>, in the server HTML too, so the focus is right before hydration. Library mode: no attribute; the Popup writes autofocus on the first enabled Cancel right before showModal() and removes it after.
AlertDialog.Action| Prop | Type | Default | Description |
|---|---|---|---|
action | Action<[details: AlertDialogActionDetails & Rejectable]> | – | The confirmed work. Runs in this button's own transition (data-pending on it), then closes the dialog with value as returnValue: in library mode through the Root (openChangeAction(false) awaited, view transition if set), in JS-free mode with close(value). A rejection reaches the nearest Error Boundary above the button and leaves the dialog open; details.reject() leaves it open with no boundary. With action the button renders no commandfor / command, so a click before hydration does nothing instead of closing the dialog as if the work had been done. Without action it only closes the dialog (a native request-close invoker in JS-free mode). details.returnValue is the value. |
whilePending | "run" | "ignore" | "ignore" | "ignore": a second click, Enter or Space while the action runs is cancelled, and the button is aria-disabled="true" meanwhile. "run": the action runs again; the dialog closes once, after the last run, if the latest resolved. |
value | string | "" | Becomes dialog.returnValue and details.returnValue. |
disabled | boolean | false | Never runs or closes. Native disabled; owned. A click runs no onClick, a render element's included, and is cancelled; a render element's disabled disables the part too (unavailable parts). |
className | string | ((state: AlertDialogActionState) => string | undefined) | – | A class name, or a function of the part's state. |
style | CSSProperties | ((state: AlertDialogActionState) => CSSProperties | undefined) | – | Inline style, or a function of the part's state. |
children | ReactNode | ((state: AlertDialogActionState) => ReactNode) | – | Content, or a function of the state: {({ pending }) => pending ? "Deleting…" : "Delete"}. |
render | ReactElement | ((props, state: AlertDialogActionState) => ReactNode) | – | Replace the default <button> (element form) or take over rendering (function form). |
AlertDialogActionState is { pending, disabled }.type (on a <button> only), disabled, aria-disabled, commandfor and command (none with action), value, onClick (library mode, or with action), data-pending, data-disabled. Owned and never written: popoverTarget, popoverTargetAction.data-pending spans the action and the close that follows. AlertDialog.Action type="submit" is not supported (type is owned): inside an AlertDialog.Form, confirm with a plain submit button.
AlertDialog.Form, AlertDialog.Title, AlertDialog.DescriptionDialog.Form, Dialog.Title and Dialog.Description, unchanged: the same props (action, closeOnSettle, method on the Form; render to change the heading level on the Title), the same state types (AlertDialogFormState is { pending }; Title and Description get the Popup's) and the same owned keys (action and method; id). See the Dialog props.
| Attribute | On | Meaning |
|---|---|---|
:open, :modal, ::backdrop | Popup | As on a Dialog. |
[role="alertdialog"] | Popup | Always. |
data-modal | Popup | Always present. |
data-open | Trigger | As on a Dialog: optimistic in library mode; in JS-free mode whether the dialog is open, written from its toggle event. |
data-pending | Trigger | Library mode: as on a Dialog. |
data-pending | Cancel, Action | From the click until the close it asked for has committed: its action, then the Root's close (library mode, also without action; a Cancel clicked while the confirm runs). |
aria-disabled | Cancel, Action | "true" with action, while data-pending with whilePending="ignore" (the default). |
data-disabled | Trigger, Cancel, Action | The disabled prop. |
One stylesheet styles a Dialog and an AlertDialog: the hooks and the transition types are the same. To tell them apart in CSS, select [role="alertdialog"].
| Key | Where | Behaviour | Who |
|---|---|---|---|
| Enter / Space | Trigger | Opens; focus moves to the Cancel. | the browser (JS-free) or the Trigger |
| Tab / Shift+Tab | Popup | Cycles through the dialog; the page is inert. | the browser |
| Escape | Popup | Closes and returns focus to the opener; onOpenChange(false, { reason: "dismiss" }). | the browser |
| Enter / Space | Cancel | Closes. | the browser (JS-free) or the Cancel |
| Enter / Space | Action | Runs the action, then closes; ignored while pending by default. | the Action |
role="alertdialog" with aria-modal from showModal(), aria-labelledby pointing at the Title and aria-describedby at the Description. The Trigger is a plain button (no aria-expanded, no aria-haspopup).aria-describedby of yours that names an element, once, when its first showing ends (a Description behind a Suspense boundary that resolves meanwhile counts).Concept: Transitions & ViewTransition
Dialog's, not an AlertDialog set: library mode tags an open with fsui-dialog plus fsui-dialog-open, a Cancel, Action or Form close with fsui-dialog plus fsui-dialog-close; Escape is a fact and carries none. To tell an alert dialog's open from a dialog's in a transition map, add your own type with addTransitionType in openChangeAction. These types are public API: key a transition map on them, and add them with addTransitionType for a controlled change (Transitions). A string transition needs neither: it is keyed on an internal per-instance type and animates this alert dialog alone.
Concept: Pending & optimistic state
The Action is a pure trigger: data-pending and state.pending from the click until the close commits, aria-disabled while it ignores a second click (the default). From the moment its action resolves the close is the Root's: the Trigger shows data-pending too. The Cancel stays active while the Action is pending; clicked meanwhile, it shows data-pending (no aria-disabled) until its close commits, when the action settles.
data-pending and aria-disabled="true"; your action runs. A second click is ignored.openChangeAction(false), reason: "activate"); when that settles the dialog closes, inside the view transition if the Popup has transition, and focus returns to the Trigger. If the action re-rendered something that suspends, the dialog stays open and the button pending until that content has committed: one transition.details.reject(): the same, with no Error Boundary; the message is yours to render.const [deleting, setDeleting] = useOptimistic(false);
<AlertDialog.Cancel disabled={deleting}>Cancel</AlertDialog.Cancel>
<AlertDialog.Action
action={async () => {
setDeleting(true); // optimistic: reverts by itself when the action settles
await deleteProject(project.id);
}}
>
Delete
</AlertDialog.Action>Escape still closes the dialog.
Concept: Suspense
As a Dialog's: content that suspends holds the open, the Trigger is pending, and the dialog opens complete with focus on the Cancel (the target is resolved right before showModal()). With a <Suspense> inside the Popup whose fallback has no Cancel, the dialog opens on the fallback and focus does not move when the Cancel arrives: keep the buttons outside that boundary.
Concept: Browser-owned state
JS-free mode: the browser owns everything. Library mode: the Trigger, Cancel, Action and Form are requests (openChangeAction); Escape is the browser's, a fact: the dialog closes at once and onOpenChange(false, { reason: "dismiss" }) is called. Cancel and Escape both mean "no" and arrive on different channels: pass the same function to both props to hear every "no".
Concept: Server Components
JS-free mode: the Trigger (command="show-modal"), the role and the wiring, the Cancel (command="request-close", with autofocus in the server HTML), Escape, the backdrop that does not dismiss, and an AlertDialog.Form with a Server Function all work from a Server Component and before hydration. An Action with action needs hydration: before it the button does nothing. Library mode: the content is not in the server HTML.
// No "use client": this file is a Server Component. The AlertDialog.Root has none of `open`,
// `defaultOpen`, `openChangeAction` or `onOpenChange`, so it runs in JS-free mode: the Trigger is
// a native `command="show-modal"` invoker, Cancel is a `command="request-close"` button that
// carries `autofocus` in the server HTML, and Delete submits the AlertDialog.Form. The browser
// opens, focuses Cancel, closes on Escape (not on a backdrop click) and returns focus, before
// hydration and with JavaScript off.
//
// This site is static, so the form has no Server Function and closes the dialog
// (`method="dialog"`). In an app with a server, pass yours, `action={deleteProject}`, and keep
// everything else: the form then posts before hydration and runs the action after it.
import { AlertDialog } from "@funstack/ui/alert-dialog";
export function AlertDialogServerConfirm() {
return (
<AlertDialog.Root>
<AlertDialog.Trigger className="demo-button demo-danger">Delete project…</AlertDialog.Trigger>
<AlertDialog.Popup className="demo-dialog">
<AlertDialog.Title>Delete "Atlas"?</AlertDialog.Title>
<AlertDialog.Description>This cannot be undone.</AlertDialog.Description>
<AlertDialog.Form className="demo-dialog-actions">
<input type="hidden" name="id" value="atlas" />
<AlertDialog.Cancel className="demo-button">Cancel</AlertDialog.Cancel>
<button type="submit" className="demo-button demo-danger" value="delete">
Delete
</button>
</AlertDialog.Form>
</AlertDialog.Popup>
</AlertDialog.Root>
);
}/* Dialog: the Popup is the <dialog> itself. Open state is `:open` / `:modal` on it (exact in
both modes); the Trigger carries `data-open` / `data-pending` in library mode only. */
/* CSS-only scroll lock, keyed on :modal: covers dialogs opened before hydration and nested ones. */
html:has(.demo-dialog:modal) {
overflow: hidden;
}
.demo-dialog {
inline-size: min(28rem, calc(100vw - 32px));
padding: 20px 24px;
border: 1px solid var(--color-border);
border-radius: 10px;
background: var(--color-bg);
color: var(--color-text);
box-shadow: 0 12px 40px rgb(0 0 0 / 0.3);
overscroll-behavior: contain;
}
.demo-dialog::backdrop {
background: rgb(0 0 0 / 0.45);
}
.demo-dialog h2 {
margin: 0 0 8px;
padding: 0;
border: 0;
font-size: 1.2rem;
}
.demo-dialog p {
margin: 0 0 12px;
color: var(--color-text-secondary);
}
/* Enter and exit with CSS, both modes. Enter works everywhere; the exit animates in Chromium
(with `overlay`) and Safari and is instant in Firefox. */
.demo-dialog,
.demo-dialog::backdrop {
opacity: 0;
transition:
opacity 150ms,
translate 150ms,
display 150ms allow-discrete,
overlay 150ms allow-discrete;
}
.demo-dialog {
translate: 0 8px;
}
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 1;
translate: 0 0;
}
@starting-style {
.demo-dialog:open,
.demo-dialog:open::backdrop {
opacity: 0;
}
.demo-dialog:open {
translate: 0 8px;
}
}
/* With `transition`, a view transition animates the library-driven opens and closes (a Close
part, a Form, a controlled close), Firefox included; dismissals (Escape, a click on the
backdrop) are the browser's and keep the CSS exit above.
The library keeps the two apart; no extra rule is needed. */
::view-transition-new(.demo-dialog-pop) {
animation: 180ms ease-out both demo-dialog-pop-in;
}
::view-transition-old(.demo-dialog-pop) {
animation: 140ms ease-in both demo-dialog-pop-out;
}
@keyframes demo-dialog-pop-in {
from {
opacity: 0;
scale: 0.96;
}
}
@keyframes demo-dialog-pop-out {
to {
opacity: 0;
scale: 0.96;
}
}
@media (prefers-reduced-motion: reduce) {
.demo-dialog,
.demo-dialog::backdrop {
transition: none;
}
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}
.demo-dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
.demo-dialog-form label {
display: grid;
gap: 4px;
}
.demo-dialog-form input {
padding: 0.35em 0.6em;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-bg);
color: var(--color-text);
font: inherit;
}
.demo-dialog-details {
display: grid;
grid-template-columns: auto 1fr;
gap: 4px 16px;
margin: 0;
}
.demo-dialog-details dd {
margin: 0;
}
/* The Trigger in library mode: optimistic open and pending. */
.demo-button[data-open] {
border-color: var(--color-primary);
color: var(--color-primary);
}
.demo-button[data-pending] {
cursor: progress;
}
/* A Cancel clicked while the confirm runs: pending until its close commits (the close waits for
the confirm). The delay keeps a close that commits at once from flashing. */
.demo-cancel[data-pending] {
opacity: 0.6;
transition: opacity 0s 150ms;
}
ul.demo-list {
margin: 0 0 12px;
padding: 0;
list-style: none;
}
ul.demo-list .demo-row {
justify-content: space-between;
max-inline-size: 20rem;
padding-block: 4px;
}This confirmation is a Server Component. The site is static, so its form only closes the dialog; with a server, pass a Server Function and nothing else changes:
// A Server Component; deleteProject is a Server Function ("use server").
<AlertDialog.Root>
<AlertDialog.Trigger>Delete project</AlertDialog.Trigger>
<AlertDialog.Popup>
<AlertDialog.Title>Delete "{project.name}"?</AlertDialog.Title>
<AlertDialog.Description>This cannot be undone.</AlertDialog.Description>
<AlertDialog.Form action={deleteProject}>
<input type="hidden" name="id" value={project.id} />
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<button type="submit">Delete</button>
</AlertDialog.Form>
</AlertDialog.Popup>
</AlertDialog.Root>| `AlertDialog.Form action` + submit button | `AlertDialog.Action action` | |
|---|---|---|
| Before hydration | the form posts to the Server Function; the page is rendered again | the button does nothing |
| After hydration | React runs the action; the dialog closes when its transition settles | the action runs in the button's transition, then the close |
| Pending | useFormStatus() in the submit button, AlertDialogFormState.pending | data-pending / state.pending on the Action |
| Rejection | Error Boundary; the dialog stays open | Error Boundary; the dialog stays open |
| Arguments | FormData (hidden inputs) | a closure |
AlertDialog.Form is Dialog.Form: with a function action it closes the dialog once the action's transition settles without throwing; rendered as a Form.Root it also waits for a result without field errors, so a confirm that needs inline errors next to live buttons is a Form (see Dialog: Forms). Confirm with a plain <button type="submit"> inside it, not an AlertDialog.Action: the form is React's own channel, and an Action inside it would be a second owner of the same click.
Open the dialog with an urgent setConfirming(true) in a click handler on the item's render element, and give the item no action. State set inside an action is a transition update, so a dialog opened from the item's action waits for every action pending in the app (Pending actions hold other transitions). The Menu recipe explains the item's side.
const [confirming, setConfirming] = useState(false);
<Menu.Item render={<button onClick={() => setConfirming(true)} />}>Delete…</Menu.Item>
{/* The handler alone: Cancel, the Action's close and Escape all close at once. */}
<AlertDialog.Root open={confirming} onOpenChange={setConfirming}>
<AlertDialog.Popup>
<AlertDialog.Title>Delete 3 files?</AlertDialog.Title>
<AlertDialog.Description>They are moved to the trash.</AlertDialog.Description>
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<AlertDialog.Action action={moveToTrash}>Move to trash</AlertDialog.Action>
</AlertDialog.Popup>
</AlertDialog.Root>Measured with a 1.5 s save pending elsewhere: opened from the item's action, the dialog appeared after about 1.4 s, when the save settled; opened from the click handler, within 20 ms (Chromium and Firefox, click and Enter alike). In both cases focus moves to Cancel, and Escape returns it to the menu's Trigger.
Closing waits for nothing either. The Root has open and onOpenChange and no openChangeAction, so there is nobody to ask: Cancel, and the Action once its action resolved, close the dialog in the event and tell onOpenChange(false, { reason: "activate", returnValue }), where setConfirming adopts it. Escape is a dismissal, reported the same way with "dismiss". What this shape costs:
open at true sees the dialog close and open again.transition.action runs closes the dialog; the work goes on, and a later failure reaches reportError only. Make Cancel unavailable while the work runs if the user must stay.AlertDialog.Trigger does nothing there (a development warning says so).With openChangeAction={setConfirming} added, Cancel asks the Root to close and the request runs in the Root's transition, so while a save is pending elsewhere it waits for it too: about 1.4 s in the same test, unless an urgent setConfirming(false) of your own closes the dialog first.
The nested confirm of the Dialog recipes, with the inner Root written as an AlertDialog.Root: "Keep editing" is its Cancel (focused on open), "Discard" its Action. Keep the inner Root JS-free so it opens synchronously in the click; no action awaits the user's answer.
<AlertDialog.Root
open={open}
openChangeAction={async (next, { returnValue }) => {
if (!next && returnValue === "discard") await discardDraft();
startTransition(() => setOpen(next));
}}
onOpenChange={setOpen}
>
…
<AlertDialog.Cancel>Keep editing</AlertDialog.Cancel>
<AlertDialog.Action value="discard">Discard</AlertDialog.Action>Here the pending state shows on the Trigger, not on the Action, and a rejection goes to the boundary above the Root, which removes the dialog. Prefer the Action's action.