When to use it#
- Use an alert dialog when the user must answer before going on, and the answer matters: an action that can’t be undone, or a session that is about to end.
- Use it in a page or a form for residents and in staff tools alike. Opening it on page load is for system messages only, such as the session timeout warning.
- Not for a form or a read the user may dismiss: that is a Dialog.
- Not for a message that is part of the page: use an Alert.
- Not for a multi-step form or long reading: use a page.
Example#
import { AlertDialog } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useAlertDialogTexts } from './texts.ts'
export function ConfirmDelete() {
const { texts } = useAlertDialogTexts()
const [open, setOpen] = useState(false)
const [isDeleted, setIsDeleted] = useState(false)
const keepReference = useRef<HTMLButtonElement>(null)
return (
<>
<AlertDialog.Root open={open} onOpenChange={setOpen} initialFocusRef={keepReference}>
<AlertDialog.Trigger className="kv-button">{texts.deleteDraft}</AlertDialog.Trigger>
<AlertDialog.Popup>
<AlertDialog.Title>{texts.deleteTitle}</AlertDialog.Title>
<AlertDialog.Description>{texts.deleteDescription}</AlertDialog.Description>
<AlertDialog.Actions>
<button
type="button"
className="kv-button kv-button--danger"
onClick={() => {
setIsDeleted(true)
setOpen(false)
}}
>
{texts.deleteConfirm}
</button>
<AlertDialog.Close ref={keepReference} className="kv-button">
{texts.deleteKeep}
</AlertDialog.Close>
</AlertDialog.Actions>
</AlertDialog.Popup>
</AlertDialog.Root>
<output>{isDeleted ? texts.deleted : null}</output>
</>
)
}Use cases#
Warn before a session ends
A system opens the alert dialog, so there may be no trigger to return to. Pass finalFocusRef, so focus has somewhere to go, and initialFocusRef on the primary action. Give the clock time, and update the minutes left in a status line inside the dialog.
import { AlertDialog, useFormat } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { useAlertDialogTexts } from './texts.ts'
const secondsToExpiry = 120
export function TimeoutWarning() {
const { texts } = useAlertDialogTexts()
const format = useFormat()
const [open, setOpen] = useState(false)
const [expiresAt, setExpiresAt] = useState(0)
const [minutesLeft, setMinutesLeft] = useState(secondsToExpiry / 60)
const [outcome, setOutcome] = useState<string | undefined>()
const stayReference = useRef<HTMLButtonElement>(null)
const returnReference = useRef<HTMLButtonElement>(null)
useEffect(() => {
if (!open) {
return undefined
}
const timer = setInterval(() => {
const secondsLeft = Math.ceil((expiresAt - Date.now()) / 1000)
if (secondsLeft <= 0) {
setOpen(false)
setOutcome(texts.signedOut)
} else {
setMinutesLeft(Math.ceil(secondsLeft / 60))
}
}, 1000)
return () => clearInterval(timer)
}, [open, expiresAt, texts.signedOut])
return (
<>
<button
ref={returnReference}
type="button"
className="kv-button"
onClick={() => {
setExpiresAt(Date.now() + secondsToExpiry * 1000)
setMinutesLeft(secondsToExpiry / 60)
setOutcome(undefined)
setOpen(true)
}}
>
{texts.showTimeout}
</button>
<AlertDialog.Root
open={open}
onOpenChange={(nextOpen) => {
setOpen(nextOpen)
if (!nextOpen) {
setOutcome(texts.stayed)
}
}}
initialFocusRef={stayReference}
finalFocusRef={returnReference}
>
<AlertDialog.Popup>
<AlertDialog.Title>{texts.timeoutTitle}</AlertDialog.Title>
<AlertDialog.Description>
{texts.timeoutDescription(format.date(expiresAt, { timeStyle: 'short' }))}
</AlertDialog.Description>
<AlertDialog.Body>
<output>{texts.timeoutRemaining(minutesLeft)}</output>
</AlertDialog.Body>
<AlertDialog.Actions>
<AlertDialog.Close ref={stayReference} className="kv-button kv-button--primary">
{texts.timeoutStay}
</AlertDialog.Close>
<button
type="button"
className="kv-button"
onClick={() => {
setOpen(false)
setOutcome(texts.signedOut)
}}
>
{texts.timeoutSignOut}
</button>
</AlertDialog.Actions>
</AlertDialog.Popup>
</AlertDialog.Root>
<output>{outcome}</output>
</>
)
}Props in this example:
initialFocusRefon AlertDialog.RootfinalFocusRefon AlertDialog.Root
Warning: Don't forget
Say that the answers are kept, and make “Stay signed in” really keep the session going (2.2.1 Timing Adjustable). Escape closes the dialog too, so it must do the same as “Stay signed in”, never sign the user out.
Delete the cases chosen in a list
A case worker chooses several cases and deletes them. Put what will be deleted in the Body, so the answer is made with the facts in view, and say how many in the title and on the button. Render the safe action with your own Button component: as={Button} on AlertDialog.Close.
import { AlertDialog, Button } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useAlertDialogTexts } from './texts.ts'
export function DeleteCases() {
const { texts } = useAlertDialogTexts()
const [open, setOpen] = useState(false)
const [outcome, setOutcome] = useState<string | undefined>()
const keepReference = useRef<HTMLButtonElement>(null)
return (
<>
<AlertDialog.Root open={open} onOpenChange={setOpen} initialFocusRef={keepReference}>
<AlertDialog.Trigger className="kv-button">{texts.deleteCases}</AlertDialog.Trigger>
<AlertDialog.Popup>
<AlertDialog.Title>{texts.casesTitle}</AlertDialog.Title>
<AlertDialog.Description>{texts.casesDescription}</AlertDialog.Description>
<AlertDialog.Body>
<ul>
{texts.caseNumbers.map((caseNumber) => (
<li key={caseNumber}>{caseNumber}</li>
))}
</ul>
</AlertDialog.Body>
<AlertDialog.Actions>
<Button
className="kv-button--danger"
onClick={() => {
setOutcome(texts.casesDeleted)
setOpen(false)
}}
>
{texts.casesConfirm}
</Button>
<AlertDialog.Close as={Button} ref={keepReference}>
{texts.casesKeep}
</AlertDialog.Close>
</AlertDialog.Actions>
</AlertDialog.Popup>
</AlertDialog.Root>
<output>{outcome}</output>
</>
)
}Props in this example:
initialFocusRefon AlertDialog.Rootason AlertDialog.Close
Discard changes made in a dialog
Closing a Dialog with changes in it loses them. Keep the dialog open, and open an alert dialog from inside it. Escape and Close ask first, and “Keep editing” is where focus starts.
Email address: anna.lindberg@example.com
import { AlertDialog, Dialog, Field, TextInput } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useAlertDialogTexts } from './texts.ts'
export function DiscardChanges() {
const { texts } = useAlertDialogTexts()
const [isEditing, setIsEditing] = useState(false)
const [isAsking, setIsAsking] = useState(false)
const [savedEmail, setSavedEmail] = useState(texts.savedEmail)
const [draftEmail, setDraftEmail] = useState(texts.savedEmail)
const keepEditingReference = useRef<HTMLButtonElement>(null)
const hasChanges = draftEmail !== savedEmail
return (
<>
<Dialog.Root
open={isEditing}
onOpenChange={(nextOpen) => {
if (nextOpen) {
setDraftEmail(savedEmail)
setIsEditing(true)
} else if (hasChanges) {
// Escape and Close are requests. Keep the dialog open and ask first.
setIsAsking(true)
} else {
setIsEditing(false)
}
}}
>
<Dialog.Trigger className="kv-button">{texts.changeEmail}</Dialog.Trigger>
<Dialog.Popup>
<Dialog.Title>{texts.changeEmailTitle}</Dialog.Title>
<Dialog.Description>{texts.changeEmailText}</Dialog.Description>
<form
onSubmit={(event) => {
event.preventDefault()
setSavedEmail(draftEmail)
setIsEditing(false)
}}
>
<Dialog.Body>
<Field.Root required>
<Field.Label>{texts.emailAddress}</Field.Label>
<TextInput
type="email"
autoComplete="email"
value={draftEmail}
onChange={(event) => setDraftEmail(event.target.value)}
/>
</Field.Root>
</Dialog.Body>
<Dialog.Actions>
<button type="submit" className="kv-button kv-button--primary">
{texts.saveEmail}
</button>
<Dialog.Close className="kv-button">{texts.closeEmail}</Dialog.Close>
</Dialog.Actions>
</form>
<AlertDialog.Root
open={isAsking}
onOpenChange={setIsAsking}
initialFocusRef={keepEditingReference}
>
<AlertDialog.Popup>
<AlertDialog.Title>{texts.discardTitle}</AlertDialog.Title>
<AlertDialog.Description>{texts.discardDescription}</AlertDialog.Description>
<AlertDialog.Actions>
<button
type="button"
className="kv-button kv-button--danger"
onClick={() => {
setIsAsking(false)
setIsEditing(false)
}}
>
{texts.discardConfirm}
</button>
<AlertDialog.Close ref={keepEditingReference} className="kv-button">
{texts.discardKeep}
</AlertDialog.Close>
</AlertDialog.Actions>
</AlertDialog.Popup>
</AlertDialog.Root>
</Dialog.Popup>
</Dialog.Root>
<p>
{texts.emailIs} {savedEmail}
</p>
</>
)
}Props in this example:
openon AlertDialog.RootonOpenChangeon AlertDialog.RootinitialFocusRefon AlertDialog.Root
Information: Did you know?
Escape closes the alert dialog only, and the Dialog stays open. It reports escape to onOpenChange: answer it with “Keep editing”, never with a discard.
Delete a booking when the delete fails
A confirm button can fail. Keep the alert dialog open, so nothing is lost, and show the error inside it with an Alert. The page behind a modal dialog is inert, so the page’s live regions (the areas a screen reader watches for new text) are silent while it is open. The dialog hosts its own, and an Alert with announce is read out through it.
Delete the booking on 14 March at 10:30?
You can’t undo this. The time becomes free for other people.
import { Alert, AlertDialog } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useAlertDialogTexts } from './texts.ts'
export function FailedDelete() {
const { texts } = useAlertDialogTexts()
const [open, setOpen] = useState(false)
const [tries, setTries] = useState(0)
const [hasFailed, setHasFailed] = useState(false)
const [isDeleted, setIsDeleted] = useState(false)
const keepReference = useRef<HTMLButtonElement>(null)
const deleteBooking = () => {
// A real app asks the server. Here the first try fails, so the error shows.
if (tries === 0) {
setTries(1)
setHasFailed(true)
return
}
setHasFailed(false)
setIsDeleted(true)
setOpen(false)
}
return (
<>
<AlertDialog.Root
open={open}
onOpenChange={(nextOpen) => {
setOpen(nextOpen)
if (!nextOpen) {
setHasFailed(false)
}
}}
initialFocusRef={keepReference}
>
<AlertDialog.Trigger className="kv-button">{texts.deleteBooking}</AlertDialog.Trigger>
<AlertDialog.Popup>
<AlertDialog.Title>{texts.bookingTitle}</AlertDialog.Title>
<AlertDialog.Description>{texts.bookingDescription}</AlertDialog.Description>
<AlertDialog.Body>
{hasFailed ? (
<Alert.Danger announce="polite">
<Alert.Title as="p">{texts.bookingFailed}</Alert.Title>
</Alert.Danger>
) : null}
</AlertDialog.Body>
<AlertDialog.Actions>
<button type="button" className="kv-button kv-button--danger" onClick={deleteBooking}>
{texts.bookingConfirm}
</button>
<AlertDialog.Close ref={keepReference} className="kv-button">
{texts.bookingKeep}
</AlertDialog.Close>
</AlertDialog.Actions>
</AlertDialog.Popup>
</AlertDialog.Root>
<output>{isDeleted ? texts.bookingDeleted : null}</output>
</>
)
}Props in this example:
openon AlertDialog.RootonOpenChangeon AlertDialog.Root
Accessibility#
What it does for you#
- APG pattern: Alert Dialog, a Dialog (Modal) for a message that needs an answer. It shares its hook, focus rules and layer behaviour with Dialog: see the Dialog page for everything not listed here.
- Deviations: Tab does not cycle inside the dialog, as in Dialog: a native modal
<dialog>lets Tab leave to browser UI before it wraps. Approved by the maintainer. - Native elements used:
<dialog role="alertdialog">(Popup),<button>(Trigger),<h2>(Title),<p>(Description),<div>(Body, Actions). Nothing for Root.
An AlertDialog interrupts the user with a message that needs an answer: a confirm-before-delete, a session timeout warning. It starts on the safe or the primary action, it is read out together with its message, and a press outside never dismisses it. Escape runs the owner's cancel outcome, which must never be destructive. The dialog itself announces nothing: opening is read out because focus moves into it (the role, the name and the description). It hosts its own live regions for status inside it, because the page's are inert while it is open.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| AlertDialog.Root | none: it renders no element | none | open / defaultOpen / onOpenChange(open, { reason, event }), initialFocusRef, finalFocusRef, messages. No dismissOnOutsidePress: it is always false |
| AlertDialog.Trigger | <button type="button">, optional | aria-haspopup="dialog", data-open while open | Classes kv-dialog-trigger and kv-alert-dialog-trigger. dialog is the closest valid aria-haspopup token |
| AlertDialog.Popup | <dialog role="alertdialog">, always rendered | aria-modal="true" while open, aria-labelledby the Title, aria-describedby the Description (required). data-open while open | Classes kv-dialog and kv-alert-dialog. Its children stay mounted while it is closed |
| AlertDialog.Title | <h2 tabindex="-1"> | none. It is the popup's name | Classes kv-dialog-title and kv-alert-dialog-title |
| AlertDialog.Description | <p> | none. It is the popup's description, read out with the title | Classes kv-dialog-description and kv-alert-dialog-description. The consequence, and whether it can be undone |
| AlertDialog.Body | <div> | none | Classes kv-dialog-body and kv-alert-dialog-body |
| AlertDialog.Actions | <div> | none | Classes kv-dialog-actions and kv-alert-dialog-actions. The consumer's buttons, or AlertDialog.Close |
| AlertDialog.Close | <button type="button"> | none of its own. Children are its name | Class kv-alert-dialog-close. A plain button: no icon, no default text. Closes with reason close-press. The consumer styles it |
useAlertDialog | the same attributes, for your own elements | as useDialog, with role="alertdialog" and no outside-press dismissal | closeProps is there for your own button and carries no aria-label: the button's text is its name. Options as the Root |
Rules, tested in alert-dialog.test.tsx (the rest in dialog.test.tsx):
- Role and description.
role="alertdialog", witharia-describedbyon the Description. An alert dialog without a Description warns in development: it is read out with its message. - Never dismissed by a press outside. The layer still shields the layers below. A backdrop press and a touch lift do nothing, whatever the owner does.
- Escape is reported as
escapetoonOpenChange. The owner answers with the safe outcome, or keeps it open by not changingopen. - Initial focus is
initialFocusRef: the least destructive action ("Keep draft"), or the primary one when nothing is destroyed ("Stay signed in"). Without it focus starts on the Title, not the first control (which may be the destructive one), and a development warning fires, because the first control would be chosen by chance. - Nesting. An AlertDialog can open over a Dialog: Escape closes the AlertDialog first.
as.AlertDialog.Closetakes a component (as={Button}) that must render a button and spread its props on a DOM node; its props are plain props, merged with the part's. Allowed elements: Title, Description, Body and Actions take the same tags as the Dialog parts (Titleh2toh6, Descriptionpordiv, Body and Actionsdivorsection); another tag warns once.AlertDialog.Popup(a native<dialog>) andAlertDialog.Triggerhave noas.- Dev warnings: no Description, no
initialFocusRef, no name, anAlertDialog.Closewith no name, and the shared ones (a part outside a Root, no place for focus to return).
It announces nothing.
What you need to do#
- Title: the question the buttons answer ("Do you want to delete the draft?"). Never "Are you sure?", "Warning" or "Confirm".
- Description: the consequence, and whether it can be undone, in one or two short sentences. Required.
- Buttons: verb and object ("Delete the draft", "Keep the draft"). The primary action first in the DOM. Never "OK", "Yes" or "No". Avoid "Cancel" when it could mean cancelling the whole application: say what is kept ("Keep the draft").
- Set
initialFocusRefto the safe action when something is destroyed, or to the primary action when nothing is. - Escape must never destroy. Answer
escapewith the cancel outcome. - Close it with
AlertDialog.Close, or from your own buttons by settingopentofalse(controlled). Move focus where the pattern says if the trigger is gone. - A timeout warning gives the clock time and the minutes, says that answers are saved (2.2.1 Timing Adjustable, A), announces the countdown politely once a minute, and passes
finalFocusRef. - Everything on the Button page applies to the buttons.
Information: Implement like this
Write the title as the question the buttons answer, and each button as a verb and an object, so it makes sense alone. Avoid “Cancel” when it could mean cancelling the whole application: say what is kept, such as “Keep draft”.
Visual and modes#
- Look: the same as the Dialog. On a narrow screen it is a sheet at the bottom, as wide as the screen. On a wider screen it is a centred box. The page behind is dimmed, and the backdrop only dims.
- Focus indicator: the trigger and the actions are Buttons, so they have the Button's focus ring (2.4.7 Focus Visible, AA). The Title shows the same ring after a keyboard open.
- Target size: the buttons are at least 24 × 24 CSS px, and taller in the default theme (2.5.8 Target Size (Minimum), AA).
- Colour: the dialog's text has at least 4.5:1 contrast on its surface (1.4.3 Contrast (Minimum), AA). A destructive confirm is a danger button with the words carrying the risk, never colour alone (1.4.1 Use of Color, A).
- forced-colors behaviour (Windows contrast themes): the dialog keeps a visible edge in the system text colour on all sides, so the open state is never shown by colour alone. The forced-colours sweep checks that every part keeps a visible boundary and shows a focus indicator when it has focus (1.4.11).
- reduced-motion behaviour: opening fades in only when the user allows motion. Closing is always instant, so focus returns at once.
- Reflow: no fixed width or height. At 320 CSS px and 400% zoom it needs no horizontal scrolling, and it scrolls inside when it is too tall (1.4.10 Reflow, AA). The reflow sweep runs every story at 320 CSS px and fails on horizontal overflow; 400% zoom is reviewed in the stories.
- Text spacing (1.4.12 Text Spacing, AA): the text-spacing sweep applies the spacing to every story and fails on a box that clips its content.
- RTL: logical properties only. The actions start at the inline start.
Information: Did you know?
While it is open, the <html> element has data-kv-scroll-locked. The default theme turns it into overflow: hidden. Without the theme, add that rule yourself: the headless package ships no CSS.
Focus management#
- Initial focus:
initialFocusRef(else the Title, never the first control), the least destructive action (a destructive confirm: "Keep draft") or the primary one ("Stay signed in" in a timeout warning).AlertDialog.Closeis an ordinary action: it can be the initial focus. - Trap: native, as Dialog. The page is
inert, and Tab leaves to browser UI before it wraps (approved deviation). - Restore to:
finalFocusRef, the Trigger, the element focused before it opened, in that order, neverbody. See the Dialog page. A system-opened alert dialog (a timer) has no Trigger: passfinalFocusRef. - Never obscured by: nothing is pinned, and long content scrolls inside the popup.
WCAG success criteria#
- 1.3.1 Info and Relationships (A) and 4.1.2 Name, Role, Value (A): the role
alertdialog, the name from the Title and the description (alert-dialog.test.tsx › an open alert dialog is modal, has role alertdialog, a name, a description and no axe violations). - 1.4.10 Reflow (AA): the sheet and the scroll inside it (the reflow sweep runs every story at 320 CSS px and fails on horizontal overflow).
- 1.4.12 Text Spacing (AA): the text-spacing sweep applies the spacing to every story and fails on a box that clips its content.
- 2.1.1 Keyboard (A), 2.1.2 No Keyboard Trap (A) and 2.4.3 Focus Order (A): native keys and Escape, Tab can always leave to the browser, and focus goes in on open and back on close (
alert-dialog.test.tsx › Escape reports escape, closes the alert dialog and returns focus to the trigger). - 2.2.1 Timing Adjustable (A): for a timeout warning. This is the consumer's block, see Consumer responsibilities.
- 2.4.7 Focus Visible (AA) and 2.4.11 Focus Not Obscured (Minimum) (AA): the buttons' focus ring, and nothing is pinned, so nothing covers the focused control.
- 2.5.8 Target Size (Minimum) (AA): the buttons are at least 24 × 24 CSS px.
- 3.3.4 Error Prevention (Legal, Financial, Data) (AA): a confirm step before an irreversible action. It helps a page meet this criterion, and whether the page does depends on your flow.
- 4.1.3 Status Messages (AA): the dialog's own live regions (
alert-dialog.test.tsx › a component inside announces in the alert dialog’s own live region).
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
| Key | Where | What happens |
|---|---|---|
| Tab | before the trigger | Moves focus to the trigger. The trigger is one stop Test: alert-dialog.test.tsx › Tab focuses the trigger, and is one stop |
| Shift+Tab | on the trigger | Moves focus to the previous focusable element Test: alert-dialog.test.tsx › Shift+Tab leaves the trigger backwards |
| Enter / Space | on the trigger | Opens the alert dialog. Focus moves to initialFocusRef, the safe or primary action, else the TitleTest: alert-dialog.test.tsx › Enter and Space on the trigger open it, and focus starts on initialFocusRef, alert-dialog.test.tsx › initial focus is initialFocusRef, the safe action, not the first control |
| Tab / Shift+Tab | inside | Moves to the next or previous tabbable element inside, in DOM order. At either end focus leaves to browser UI and wraps (the approved deviation) Test: alert-dialog.test.tsx › Tab and Shift+Tab move between the tabbable elements inside, in DOM order |
| Tab / Shift+Tab | any | The page behind is never reached: it is inertTest: alert-dialog.test.tsx › Tab and Shift+Tab never reach the page behind the dialog |
| Escape | inside, no other layer open | Reports escape. The owner closes it with the safe outcome, and focus returns, or refuses and it stays openTest: alert-dialog.test.tsx › Escape reports escape, closes the alert dialog and returns focus to the trigger, alert-dialog.test.tsx › Escape that the owner refuses keeps the alert dialog open |
| Escape | an alert dialog over a dialog | Closes the alert dialog only. The next Escape closes the dialog Test: alert-dialog.test.tsx › Escape closes an alert dialog over a dialog first, then the dialog |
| Enter / Space | on Close | Closes with reason close-press and returns focus. A controlled owner can refuseTest: alert-dialog.test.tsx › Enter and Space on Close close the alert dialog with reason close-press, and focus returns, alert-dialog.test.tsx › a controlled owner may refuse a Close press, and the alert dialog stays open |
| Enter / Space | on an action | The button's own: the owner closes the dialog from it Test: alert-dialog.test.tsx › Enter and Space on an action are the button’s own, and the consumer closes it |
| Pointer press | on the backdrop | Nothing, ever. A touch lift does nothing either Test: alert-dialog.test.tsx › a press on the backdrop never closes an alert dialog |
| Pointer press | inside | Nothing Test: alert-dialog.test.tsx › a press inside the alert dialog does nothing |
The alert dialog handles no other key. Escape is read on the document, after the page's handlers.
API reference#
import { AlertDialog, useAlertDialog } from '@kvirn-ui/react'AlertDialog.Root
Renders no element. It owns the open state, passes it to the parts inside it and hosts the live regions for what is inside the dialog. It has no dismissOnOutsidePress: a press on the backdrop never closes an alert dialog.
| Prop | Type | Default | Description |
|---|---|---|---|
open | boolean | – | Controlled: whether the dialog is open. Pair it with onOpenChange. |
defaultOpen | boolean | false | Uncontrolled: whether the dialog starts open. |
finalFocusRef | RefObject<HTMLElement | null> | – | Where focus goes when it closes. Default: the trigger, else what had focus before it opened. Set it when the trigger can disappear or there is no trigger. |
initialFocusRef | RefObject<HTMLElement | null> | – | Where focus goes when it opens. Set it: the least destructive action, or the primary one when nothing is destroyed. A development warning fires without it. Without it focus starts on the title. |
onOpenChange | (open: boolean, details: DialogChangeDetails) => void | – | Called on every request to open or close. It only reports: with open set, you change open yourself, and if you keep it open the alert dialog stays. details.reason is trigger-press, close-press, escape or native-close (the browser closed it). It is never outside-press: a press on the backdrop does nothing. Answer escape with the safe outcome. details.event is the native event. |
children | ReactNode | – | The Trigger, if any, and the Popup. Root renders no element. |
AlertDialog.Trigger
Renders <button type="button">, optional: a dialog opened by a timer has none. It takes every attribute of a <button> and passes ref to it.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog-trigger, kv-alert-dialog-trigger | always | The part classes. |
aria-haspopup | "dialog" | The trigger opens a dialog. |
data-open | present or absent | The alert dialog is open. |
AlertDialog.Popup
Renders <dialog> shown with showModal(), in the top layer. It is always rendered and hidden while it is closed, and its children stay mounted.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog, kv-alert-dialog | always | The part classes. |
role | "alertdialog" | A modal alert dialog, shown with showModal(). It is read out with its description. |
aria-labelledby, aria-describedby | the title’s and description’s ids | Present while the Title and the Description are rendered. |
data-open | present or absent | The alert dialog is open. |
data-kv-scroll-locked | present or absent, on <html> | Set while it is open. The default theme turns it into overflow: hidden. Without the theme, add that CSS yourself. |
AlertDialog.Title
Renders <h2> that names the alert dialog: the question the buttons answer.
| Prop | Type | Default | Description |
|---|---|---|---|
as | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'h2' | The heading level, so the title fits the page’s outline. Another tag warns once in development and renders an h2. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog-title, kv-alert-dialog-title | always | The part class. |
tabindex | "-1" | Focus lands here when nothing tabbable comes first, so a long read starts at the top. |
AlertDialog.Description
Renders <p> with the consequence. Always give one: a screen reader (software that reads the screen aloud) reads it out with the title.
| Prop | Type | Default | Description |
|---|---|---|---|
as | 'p' | 'div' | 'p' | Use div when the description has more than one paragraph. Another tag warns once in development and renders a p. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog-description, kv-alert-dialog-description | always | The part class. |
AlertDialog.Body
Renders <div> for content between the description and the actions.
| Prop | Type | Default | Description |
|---|---|---|---|
as | 'div' | 'section' | 'div' | Another tag warns once in development and renders a div. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog-body, kv-alert-dialog-body | always | The part class. |
AlertDialog.Actions
Renders <div> for your buttons, the primary one first.
| Prop | Type | Default | Description |
|---|---|---|---|
as | 'div' | 'section' | 'div' | Another tag warns once in development and renders a div. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog-actions, kv-alert-dialog-actions | always | The part class. |
AlertDialog.Close
Renders <button type="button"> that closes the alert dialog with the reason close-press and returns focus. Its children are its name: say what it does (“Keep draft”). It has no icon and no default text, and a development warning fires without a name. It is an ordinary action, so it can be the initialFocusRef. Pass as={Button} to render your own button component.
| Prop | Type | Default | Description |
|---|---|---|---|
as | ElementType | 'button' | A component to render instead of the button, with its props set on the Close: as={Button} className="kv-button--primary". It must render a button, forward its ref and spread its props on a DOM node. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-alert-dialog-close | always | The part class. |
useAlertDialog
The same result as useDialog, with role="alertdialog" on the popup and a backdrop press that never closes it. Render your own live regions if the content announces.
Options
| Prop | Type | Default | Description |
|---|---|---|---|
open | boolean | – | Controlled: whether the dialog is open. Pair it with onOpenChange. |
defaultOpen | boolean | false | Uncontrolled: whether the dialog starts open. |
finalFocusRef | RefObject<HTMLElement | null> | – | Where focus goes when it closes. Default: the trigger, else what had focus before it opened. Set it when the trigger can disappear or there is no trigger. |
initialFocusRef | RefObject<HTMLElement | null> | – | Where focus goes when it opens. Set it: the least destructive action, or the primary one when nothing is destroyed. A development warning fires without it. Without it focus starts on the title. |
onOpenChange | (open: boolean, details: DialogChangeDetails) => void | – | Called on every request to open or close. It only reports: with open set, you change open yourself, and if you keep it open the alert dialog stays. details.reason is trigger-press, close-press, escape or native-close (the browser closed it). It is never outside-press: a press on the backdrop does nothing. Answer escape with the safe outcome. details.event is the native event. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
isOpen | boolean | – | Whether the dialog is open. |
triggerProps | DialogTriggerPartProps | – | Spread on a <button>: type, aria-haspopup, data-open, ref and the click handler. |
popupProps | DialogPopupPartProps | – | Spread on a <dialog>: role, aria-modal, aria-labelledby, aria-describedby, data-open, ref and the cancel and close handlers. The browser hides a closed dialog and its children, so they can stay mounted and keep what was typed. Render them only while isOpen to start fresh each time. |
titleProps | DialogTitlePartProps | – | Spread on the title, an <h2>: id and tabIndex. |
descriptionProps | DialogDescriptionPartProps | – | Spread on the description, a <p>: id. |
closeProps | DialogClosePartProps | – | Spread on a <button> inside the popup that closes it. Drop aria-label when it has visible text. |
registerTitle | () => () => void | – | Call it from an effect in your title element. aria-labelledby appears while one is registered. Returns the cleanup. |
registerDescription | () => () => void | – | Call it from an effect in your description element. aria-describedby appears while one is registered. Returns the cleanup. |
Known issues#
- A Close without text has no name.
AlertDialog.Closehas no default name, because there is no X on an alert dialog. A screen reader user hears only "button" if you leave it empty. Always give it text that says what it does. A development warning fires without a name. - Tab can reach the browser's own controls. Tab leaves the dialog to the browser (the address bar, for example) before it comes round to the first control again. This is an approved difference from the ARIA Authoring Practices pattern. The dialog's own live region exists only while it is open, as in the Dialog.
Testing#
The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.
| AT + browser + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | alert-dialog.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | alert-dialog.test.tsx (axe and role, name and state): an open alert dialog is modal, has role alertdialog, a name, a description and no axe violations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 11 rows, each names a test in alert-dialog.test.tsx |
| Focus order and management | pass | n/a | pass | alert-dialog.test.tsx: initial focus is initialFocusRef, the safe action, not the first control |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |
Also pending, by hand: whether aria-haspopup="dialog" on an alert dialog's trigger is the best token, and whether the description is read out with the name on every screen reader.
What to check#
With a screen reader and the keyboard, try:
- Open the alert dialog: focus is on the safe action, and the title and the description are read.
- Escape closes it with the safe outcome.
- A tap on the backdrop does nothing.
- Over a Dialog, Escape closes only the alert dialog.