Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

AlertDialog

A dialog for a message that needs an answer: a confirmation before deleting, a warning that the session is about to end. It is read out together with its description, and a press outside never closes it. Focus starts on the action you choose.

Package
@kvirn-ui/react
Pattern
APG Alert Dialog
Testing
Automated. Core 0 of 2, Release 0 of 3

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#

Delete the draft application?

You can’t undo this. Your answers will be deleted.

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.

Do you want to stay signed in?

For your security, we will sign you out at 12:00 AM. Your answers are saved.

2 minutes left.

Props in this example:

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.

Delete 3 cases?

You can’t undo this. The cases and the notes on them will be deleted.

  • 2026-0142
  • 2026-0155
  • 2026-0161

Props in this example:

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.

Change email address

We send a message to the new address to confirm it.

Discard your changes?

You changed the email address and have not saved it. If you discard the change, the old address is kept.

Email address: anna.lindberg@example.com

Props in this example:

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.

Props in this example:

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.

PartElement / roleARIA / stateNotes
AlertDialog.Rootnone: it renders no elementnoneopen / defaultOpen / onOpenChange(open, { reason, event }), initialFocusRef, finalFocusRef, messages. No dismissOnOutsidePress: it is always false
AlertDialog.Trigger<button type="button">, optionalaria-haspopup="dialog", data-open while openClasses kv-dialog-trigger and kv-alert-dialog-trigger. dialog is the closest valid aria-haspopup token
AlertDialog.Popup<dialog role="alertdialog">, always renderedaria-modal="true" while open, aria-labelledby the Title, aria-describedby the Description (required). data-open while openClasses 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 nameClasses kv-dialog-title and kv-alert-dialog-title
AlertDialog.Description<p>none. It is the popup's description, read out with the titleClasses kv-dialog-description and kv-alert-dialog-description. The consequence, and whether it can be undone
AlertDialog.Body<div>noneClasses kv-dialog-body and kv-alert-dialog-body
AlertDialog.Actions<div>noneClasses 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 nameClass kv-alert-dialog-close. A plain button: no icon, no default text. Closes with reason close-press. The consumer styles it
useAlertDialogthe same attributes, for your own elementsas useDialog, with role="alertdialog" and no outside-press dismissalcloseProps 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", with aria-describedby on 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 escape to onOpenChange. The owner answers with the safe outcome, or keeps it open by not changing open.
  • 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.Close takes 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 (Title h2 to h6, Description p or div, Body and Actions div or section); another tag warns once. AlertDialog.Popup (a native <dialog>) and AlertDialog.Trigger have no as.
  • Dev warnings: no Description, no initialFocusRef, no name, an AlertDialog.Close with 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 initialFocusRef to the safe action when something is destroyed, or to the primary action when nothing is.
  • Escape must never destroy. Answer escape with the cancel outcome.
  • Close it with AlertDialog.Close, or from your own buttons by setting open to false (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.Close is 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, never body. See the Dialog page. A system-opened alert dialog (a timer) has no Trigger: pass finalFocusRef.
  • 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
KeyWhereWhat happens
Tabbefore the triggerMoves focus to the trigger. The trigger is one stop
Test: alert-dialog.test.tsx › Tab focuses the trigger, and is one stop
Shift+Tabon the triggerMoves focus to the previous focusable element
Test: alert-dialog.test.tsx › Shift+Tab leaves the trigger backwards
Enter / Spaceon the triggerOpens the alert dialog. Focus moves to initialFocusRef, the safe or primary action, else the Title
Test: 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+TabinsideMoves 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+TabanyThe page behind is never reached: it is inert
Test: alert-dialog.test.tsx › Tab and Shift+Tab never reach the page behind the dialog
Escapeinside, no other layer openReports escape. The owner closes it with the safe outcome, and focus returns, or refuses and it stays open
Test: 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
Escapean alert dialog over a dialogCloses 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 / Spaceon CloseCloses with reason close-press and returns focus. A controlled owner can refuse
Test: 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 / Spaceon an actionThe 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 presson the backdropNothing, ever. A touch lift does nothing either
Test: alert-dialog.test.tsx › a press on the backdrop never closes an alert dialog
Pointer pressinsideNothing
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.

PropTypeDefaultDescription
openboolean–Controlled: whether the dialog is open. Pair it with onOpenChange.
defaultOpenbooleanfalseUncontrolled: whether the dialog starts open.
finalFocusRefRefObject<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.
initialFocusRefRefObject<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.
childrenReactNode–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 attributeValuesMeaning
kv-dialog-trigger, kv-alert-dialog-triggeralwaysThe part classes.
aria-haspopup"dialog"The trigger opens a dialog.
data-openpresent or absentThe 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 attributeValuesMeaning
kv-dialog, kv-alert-dialogalwaysThe part classes.
role"alertdialog"A modal alert dialog, shown with showModal(). It is read out with its description.
aria-labelledby, aria-describedbythe title’s and description’s idsPresent while the Title and the Description are rendered.
data-openpresent or absentThe alert dialog is open.
data-kv-scroll-lockedpresent 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.

PropTypeDefaultDescription
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 attributeValuesMeaning
kv-dialog-title, kv-alert-dialog-titlealwaysThe 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.

PropTypeDefaultDescription
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 attributeValuesMeaning
kv-dialog-description, kv-alert-dialog-descriptionalwaysThe part class.

AlertDialog.Body

Renders <div> for content between the description and the actions.

PropTypeDefaultDescription
as'div' | 'section''div'Another tag warns once in development and renders a div.
Class or attributeValuesMeaning
kv-dialog-body, kv-alert-dialog-bodyalwaysThe part class.

AlertDialog.Actions

Renders <div> for your buttons, the primary one first.

PropTypeDefaultDescription
as'div' | 'section''div'Another tag warns once in development and renders a div.
Class or attributeValuesMeaning
kv-dialog-actions, kv-alert-dialog-actionsalwaysThe 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.

PropTypeDefaultDescription
asElementType'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 attributeValuesMeaning
kv-alert-dialog-closealwaysThe 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

PropTypeDefaultDescription
openboolean–Controlled: whether the dialog is open. Pair it with onOpenChange.
defaultOpenbooleanfalseUncontrolled: whether the dialog starts open.
finalFocusRefRefObject<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.
initialFocusRefRefObject<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

PropTypeDefaultDescription
isOpenboolean–Whether the dialog is open.
triggerPropsDialogTriggerPartProps–Spread on a <button>: type, aria-haspopup, data-open, ref and the click handler.
popupPropsDialogPopupPartProps–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.
titlePropsDialogTitlePartProps–Spread on the title, an <h2>: id and tabIndex.
descriptionPropsDialogDescriptionPartProps–Spread on the description, a <p>: id.
closePropsDialogClosePartProps–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.Close has 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 + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apassalert-dialog.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)passn/apassalert-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)passn/apass11 rows, each names a test in alert-dialog.test.tsx
Focus order and managementpassn/apassalert-dialog.test.tsx: initial focus is initialFocusRef, the safe action, not the first control
Display modes (forced colours, 320px reflow, text spacing, reduced motion)passn/apassthe four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending

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.