When to use it#
- Use a dialog for one short task or read that someone should finish or dismiss before going on: change a value, confirm details, read a notice.
- It suits a form for residents and a staff tool alike, when the content fits on one screen, also at 320 px.
- Not for a message that needs an answer, such as a confirmation before deleting: that is an AlertDialog.
- Not for a small panel next to its button that leaves the page reachable: use a Popover.
- Not for a multi-step form or long reading: use a page. Not for anything that opens on page load, except a system message such as a session timeout.
Example#
import { Dialog } from '@kvirn-ui/react'
import { useDialogTexts } from './texts.ts'
export function DefaultDialog() {
const { texts } = useDialogTexts()
return (
<Dialog.Root dismissOnOutsidePress>
<Dialog.Trigger className="kv-button">{texts.about}</Dialog.Trigger>
<Dialog.Popup>
<Dialog.Title>{texts.aboutTitle}</Dialog.Title>
<Dialog.Close />
<Dialog.Body>
<p>{texts.aboutText}</p>
</Dialog.Body>
<Dialog.Actions>
<Dialog.Close className="kv-button">{texts.close}</Dialog.Close>
</Dialog.Actions>
</Dialog.Popup>
</Dialog.Root>
)
}Use cases#
A form in a dialog
Changing one value does not need a page of its own. The title says the task, the description says what happens next, and each button says what it does. Closing with Escape or Close keeps what was typed. A press on the backdrop (the dimmed area behind the dialog) does nothing by default, so a stray tap loses nothing.
import { Dialog, Field, TextInput } from '@kvirn-ui/react'
import { useState } from 'react'
import { useDialogTexts } from './texts.ts'
export function WithAForm() {
const { texts } = useDialogTexts()
const [open, setOpen] = useState(false)
const [sentTo, setSentTo] = useState('')
return (
<>
<Dialog.Root open={open} onOpenChange={setOpen}>
<Dialog.Trigger className="kv-button">{texts.changePhone}</Dialog.Trigger>
<Dialog.Popup>
<Dialog.Title>{texts.changePhoneTitle}</Dialog.Title>
<Dialog.Close />
<Dialog.Description>{texts.changePhoneText}</Dialog.Description>
<form
onSubmit={(event) => {
event.preventDefault()
const phone = new FormData(event.currentTarget).get('phone')
setSentTo(typeof phone === 'string' ? phone : '')
setOpen(false)
}}
>
<Dialog.Body>
<Field.Root required>
<Field.Label>{texts.phoneNumber}</Field.Label>
<TextInput name="phone" type="tel" autoComplete="tel" />
</Field.Root>
</Dialog.Body>
<Dialog.Actions>
<button type="submit" className="kv-button kv-button--primary">
{texts.save}
</button>
<Dialog.Close className="kv-button">{texts.keep}</Dialog.Close>
</Dialog.Actions>
</form>
</Dialog.Popup>
</Dialog.Root>
<output>{sentTo === '' ? null : `${texts.phoneSaved} ${sentTo}.`}</output>
</>
)
}Props in this example:
openon Dialog.RootonOpenChangeon Dialog.Root
Warning: Don't forget
Put the dialog outside any form on the page. A required or invalid field in the closed dialog would otherwise stop that form from sending, with no message (3.3.1 Error Identification).
One dialog for every row of a list
A list of cases or applications can share one dialog. Open it from your own state with open, set what it shows, and leave out the Trigger. When it closes, focus goes back to the button that opened it.
Your applications
- 2024-118
- 2024-131
import { Dialog, VisuallyHidden } from '@kvirn-ui/react'
import { useId, useState } from 'react'
import { useDialogTexts } from './texts.ts'
export function ManyRows() {
const { texts } = useDialogTexts()
const headingId = useId()
const applications = [
{ number: '2024-118', received: texts.firstReceived, status: texts.waiting },
{ number: '2024-131', received: texts.secondReceived, status: texts.decided },
]
const [open, setOpen] = useState(false)
const [selectedNumber, setSelectedNumber] = useState('')
const selected = applications.find((application) => application.number === selectedNumber)
return (
<>
<p id={headingId}>{texts.applications}</p>
<ul aria-labelledby={headingId}>
{applications.map((application) => (
<li key={application.number}>
{application.number}{' '}
<button
type="button"
className="kv-button"
onClick={() => {
setSelectedNumber(application.number)
setOpen(true)
}}
>
{texts.showDetails}
<VisuallyHidden>
{' '}
{texts.forApplication} {application.number}
</VisuallyHidden>
</button>
</li>
))}
</ul>
<Dialog.Root open={open} onOpenChange={setOpen}>
<Dialog.Popup>
<Dialog.Title>
{selected === undefined
? texts.detailsTitle
: `${texts.detailsTitle} ${selected.number}`}
</Dialog.Title>
<Dialog.Close />
<Dialog.Body>
<p>
{texts.receivedOn} {selected?.received}.
</p>
<p>
{texts.status}: {selected?.status}.
</p>
</Dialog.Body>
<Dialog.Actions>
<Dialog.Close className="kv-button">{texts.close}</Dialog.Close>
</Dialog.Actions>
</Dialog.Popup>
</Dialog.Root>
</>
)
}Props in this example:
openon Dialog.RootonOpenChangeon Dialog.Root
Warning: Don't forget
If the button that opens the dialog can leave the page, pass finalFocusRef. Otherwise focus has nowhere to go back to (2.4.3 Focus Order).
Close a case and keep your place in the list
Closing a case removes its row, and the button that opened the dialog goes with it. After the case is closed, pass finalFocusRef with the list’s heading, and focus lands there. If the dialog is dismissed instead, leave it out and focus returns to the button. The heading also shows how many cases are left.
Open cases (3)
- 2026-0142: Broken streetlight on Parkgatan
- 2026-0155: Overflowing bin at the bus stop
- 2026-0161: Pothole outside the library
import { Dialog, Field, Heading, TextInput, VisuallyHidden } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useDialogTexts } from './texts.ts'
export function CloseFromList() {
const { texts } = useDialogTexts()
const [openCases, setOpenCases] = useState(texts.cases)
const [closingNumber, setClosingNumber] = useState('')
const [open, setOpen] = useState(false)
const [wasCaseClosed, setWasCaseClosed] = useState(false)
const listHeadingRef = useRef<HTMLHeadingElement>(null)
return (
<>
{/*
The button that opened the dialog is removed with its row only when the case is closed, so
finalFocusRef names the list's heading only then. Keep open, Escape and the X leave it
undefined and focus returns to the button. The heading stays on the page, and tabIndex={-1}
lets it take focus without becoming a Tab stop.
*/}
<Heading as="h4" ref={listHeadingRef} tabIndex={-1}>
{texts.openCases(openCases.length)}
</Heading>
{openCases.length === 0 ? (
<p>{texts.noOpenCases}</p>
) : (
<ul>
{openCases.map((openCase) => (
<li key={openCase.number}>
{openCase.number}: {openCase.subject}{' '}
<button
type="button"
className="kv-button"
onClick={() => {
setClosingNumber(openCase.number)
setWasCaseClosed(false)
setOpen(true)
}}
>
{texts.closeCase}
<VisuallyHidden>
{' '}
{texts.forCase} {openCase.number}
</VisuallyHidden>
</button>
</li>
))}
</ul>
)}
<p>
<button type="button" className="kv-button" onClick={() => setOpenCases(texts.cases)}>
{texts.showCasesAgain}
</button>
</p>
<Dialog.Root
open={open}
onOpenChange={setOpen}
finalFocusRef={wasCaseClosed ? listHeadingRef : undefined}
>
<Dialog.Popup>
<Dialog.Title>{texts.closeCaseTitle(closingNumber)}</Dialog.Title>
<Dialog.Close />
<Dialog.Description>{texts.closeCaseText}</Dialog.Description>
<form
// A new key per case, so the note of one case is not still there for the next.
key={closingNumber}
onSubmit={(event) => {
event.preventDefault()
setOpenCases((cases) =>
cases.filter((candidate) => candidate.number !== closingNumber),
)
setWasCaseClosed(true)
setOpen(false)
}}
>
<Dialog.Body>
<Field.Root>
<Field.Label>{texts.noteForResident}</Field.Label>
<TextInput name="note" />
</Field.Root>
</Dialog.Body>
<Dialog.Actions>
<button type="submit" className="kv-button kv-button--primary">
{texts.closeCase}
</button>
<Dialog.Close className="kv-button">{texts.keepOpen}</Dialog.Close>
</Dialog.Actions>
</form>
</Dialog.Popup>
</Dialog.Root>
</>
)
}Props in this example:
finalFocusRefon Dialog.Rootopenon Dialog.RootonOpenChangeon Dialog.Root
Warning: Don't forget
The element you pass must be able to take focus, or focus is not returned to it. A heading needs tabindex="-1". Without a place to return to, focus is lost (2.4.3 Focus Order).
Know why it closed
Keep the open state yourself when the page needs to react to it. onOpenChange says why the dialog changed. While open is set, a close is only a request: you decide whether to close it.
Closed. Last change: –
import { Dialog } from '@kvirn-ui/react'
import { useState } from 'react'
import { useDialogTexts } from './texts.ts'
export function ControlledDialog() {
const { texts } = useDialogTexts()
const [open, setOpen] = useState(false)
const [reason, setReason] = useState('–')
return (
<>
<p>
{open ? texts.stateOpen : texts.stateClosed}. {texts.lastReason} <code>{reason}</code>
</p>
<Dialog.Root
open={open}
onOpenChange={(nextOpen, details) => {
setOpen(nextOpen)
setReason(details.reason)
}}
>
<Dialog.Trigger className="kv-button">{texts.help}</Dialog.Trigger>
<Dialog.Popup>
<Dialog.Title>{texts.helpTitle}</Dialog.Title>
<Dialog.Close />
<Dialog.Body>
<p>{texts.helpText}</p>
</Dialog.Body>
<Dialog.Actions>
<Dialog.Close className="kv-button">{texts.understood}</Dialog.Close>
</Dialog.Actions>
</Dialog.Popup>
</Dialog.Root>
</>
)
}Props in this example:
openon Dialog.RootonOpenChangeon Dialog.Root
A long notice with a choice at the end
By default focus starts on the first control that is not Close. In a notice with text to read, that is a choice below the text. Pass the Title to initialFocusRef, and the dialog starts at its beginning, so the arrow keys scroll the text.
import { Dialog, Field, RadioGroup } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useDialogTexts } from './texts.ts'
export function InitialFocus() {
const { texts } = useDialogTexts()
const [open, setOpen] = useState(false)
const [delivery, setDelivery] = useState<'digital' | 'paper'>('paper')
const titleRef = useRef<HTMLHeadingElement>(null)
return (
<>
{/*
Without initialFocusRef, focus starts on the first radio button, below the text, and the
notice is skipped. The title takes focus here instead, so reading starts at the top.
*/}
<Dialog.Root open={open} onOpenChange={setOpen} initialFocusRef={titleRef}>
<Dialog.Trigger className="kv-button">{texts.readNotice}</Dialog.Trigger>
<Dialog.Popup>
<Dialog.Title ref={titleRef}>{texts.noticeTitle}</Dialog.Title>
<Dialog.Close />
<form
onSubmit={(event) => {
event.preventDefault()
const choice = new FormData(event.currentTarget).get('delivery')
setDelivery(choice === 'digital' ? 'digital' : 'paper')
setOpen(false)
}}
>
<Dialog.Body>
<p>{texts.noticeFirst}</p>
<p>{texts.noticeSecond}</p>
<RadioGroup.Root name="delivery" defaultValue="paper">
<RadioGroup.Legend>{texts.deliveryLegend}</RadioGroup.Legend>
<Field.Root>
<RadioGroup.Radio value="digital" />
<Field.Label>{texts.deliveryDigital}</Field.Label>
</Field.Root>
<Field.Root>
<RadioGroup.Radio value="paper" />
<Field.Label>{texts.deliveryPaper}</Field.Label>
</Field.Root>
</RadioGroup.Root>
</Dialog.Body>
<Dialog.Actions>
<button type="submit" className="kv-button kv-button--primary">
{texts.saveChoice}
</button>
<Dialog.Close className="kv-button">{texts.decideLater}</Dialog.Close>
</Dialog.Actions>
</form>
</Dialog.Popup>
</Dialog.Root>
<output>
{texts.lettersCome}: {delivery === 'digital' ? texts.deliveryDigital : texts.deliveryPaper}.
</output>
</>
)
}Props in this example:
initialFocusRefon Dialog.Root
Accessibility#
What it does for you#
- APG pattern: Dialog (Modal). The popup is a native
<dialog>opened withshowModal(): the browser puts it in the top layer and makes the page behind itinert. - Deviations: Tab does not cycle inside the dialog. A native modal
<dialog>lets Tab leave to the browser's own UI (the address bar) before it wraps, where the APG cycles inside. Approved by the maintainer. 2.1.2 No Keyboard Trap (A) holds: focus is never trapped, and the page behind is inert. Everything else follows the APG. - Native elements used:
<dialog>(Popup),<button>(Trigger, Close),<h2>(Title),<p>(Description),<div>(Body, Actions). Nothing for Root: it renders no element.
A Dialog is a window on top of the page that asks for the user's attention: a form, a short read, a decision. The page behind it cannot be reached with the keyboard or a screen reader, Escape and a Close button close it, focus moves in when it opens and returns to where it was when it closes, and the page does not scroll behind it. The consumer owns the markup inside. For a message that needs an answer, use an AlertDialog.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| Dialog.Root | none: it renders no element | none | Owns the open state: open / defaultOpen / onOpenChange(open, { reason, event }), initialFocusRef, finalFocusRef, dismissOnOutsidePress (default false), messages. Provides the dialog's own announcer |
| Dialog.Trigger | <button type="button">, optional | aria-haspopup="dialog", data-open while open. No aria-expanded and no aria-controls: the trigger is inert while the dialog is open | Class kv-dialog-trigger. Where focus returns to |
| Dialog.Popup | <dialog role="dialog">, always rendered | aria-modal="true" while open, aria-labelledby the Title and aria-describedby the Description, each only while that part exists. data-open while open | Class kv-dialog. Shown with showModal(). Its children stay mounted while it is closed: the browser hides and inerts them, and typed values are kept. Without a Title, give it aria-label. Closed, the browser hides it |
| Dialog.Title | <h2 tabindex="-1"> (as sets the level) | none. It is the popup's name | Class kv-dialog-title. Takes focus on open when nothing in the dialog is a better start. Never a Tab stop |
| Dialog.Description | <p> | none. It is the popup's description | Class kv-dialog-description. Optional for a Dialog, one or two short sentences |
| Dialog.Body | <div> | none | Class kv-dialog-body. Fields, prose or an Alert. Never the description |
| Dialog.Actions | <div> | none | Class kv-dialog-actions. The consumer's buttons, the primary one first |
| Dialog.Close | <button type="button"> | aria-label from dialog.close when it has no visible text. Visible text names it otherwise | Class kv-dialog-close. Place it after the Title in the DOM. Closes with reason close-press |
useDialog | the same attributes, for your own elements | isOpen, triggerProps, popupProps, titleProps, descriptionProps, closeProps, registerTitle(), registerDescription() | Options as the Root. The refs are in the props: mergeProps merges yours. A closed <dialog> hides its children, so they can stay mounted |
Each rule below has a test:
- Native modal. The popup is shown with
showModal()whenopenbecomes true and closed withclose()when it becomes false, in a layout effect, so the first paint is right.:modalmatches while open. The page behind is inert for focus, pointer and assistive technology. Nothing is portalled: the dialog is in the top layer wherever it is in the tree. - State and the browser.
cancel(a close request nobody handled) is prevented and reported asescape.close(the browser closed it, for example a<form method="dialog">) is reported asnative-close. When a controlled owner keepsopentrue after either, the dialog is shown again. Aclosethe hook caused itself is never reported. - Nested roots. A Dialog or AlertDialog inside another's Popup is closed whenever its parent is (its uncontrolled state is reset, and its
close()runs first), so closing the outer one from state also releases the inner one's scroll lock and leaves the page reachable. A controlled inner owner whoseopenstays true is shown again when the parent opens again, always after the parent (so it is the topmost modal, holds focus and closes first on Escape): set itsopentofalseif it should not. A Root next to the Popup, inside the outer Root, is not nested. OnlyDialog.Popuppasses the parent on: withuseDialogalone there is no parent, so a nested hook-only dialog stays modal when its parent closes from state: close it yourself, and do not open it in the same commit as its parent (passive effects run child-first, so the inner layer would join the stack before the outer: Escape would close the outer while the inner stays modal). - Reasons in
onOpenChange(open, { reason, event }):trigger-press,close-press,escape,outside-press,native-close. - Layers. The popup is a layer in the page's dismissable stack. Escape closes the innermost layer only: a Popover, Listbox or Combobox inside closes first, and so does a nested dialog. A press on the backdrop (the dialog element itself, outside its box) counts as outside, and closes the dialog only with
dismissOnOutsidePress. Either way the layers below do not react. - Scroll lock. While open,
data-kv-scroll-lockedis on<html>, ref-counted across dialogs (nested dialogs lock once). The hook sets no inline style:@kvirn-ui/themeturns the attribute intooverflow: hidden. Without the theme, add your own CSS. - Announcements. The provider's live regions are inert while a modal is open. Root provides its own announcer and Popup renders its live regions last, while open, so a Combobox, Table or FileUpload inside still announces. The dialog announces nothing itself: opening is announced by the focus move.
- Server rendering.
defaultOpenwrites a closed<dialog>with its content, and an effect callsshowModal(). Nothing readswindowwhile rendering. as.Dialog.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 (handlers chain,classNamejoins, refs merge). Allowed elements: Titleh2(default) toh6; Descriptionp(default) ordiv; Body and Actionsdiv(default) orsection; another tag warns once in development and falls back.Dialog.Popupis a native<dialog>andDialog.Triggera<button>: neither hasas. Class, handlers and refs merge on every part.- Development warnings: no accessible name, a part outside a Root, and no element that could take focus back.
It announces nothing.
What you need to do#
- Name the dialog: a
Dialog.Title(the question the buttons answer, or a verb phrase for a task: never "Are you sure?"), oraria-label. A development warning fires without one (4.1.2). - Say what each button does with verb and object ("Save the number"), never "OK" or "Yes". One primary action, first in the DOM.
- Give a Trigger, or
finalFocusRef. A dialog opened by a timer, with focus onbody, has nowhere to return to. - Keeps what was typed. The content stays mounted while the dialog is closed, so reopening it to finish the same task shows what was entered, with nothing typed twice (supports 3.3.7 Redundant Entry (A)). To start fresh, render
Dialog.Rootconditionally. A backdrop press does nothing by default, so no one loses input by accident. - Opening on page load is for system messages only (a session timeout). Use a page for a multi-step form or long reading.
- Scroll lock needs CSS.
@kvirn-ui/themestyleshtml[data-kv-scroll-locked]. A headless user addsoverflow: hiddenfor it. - Render the Dialog outside a page
<form>. The content stays mounted while closed, so a Popup inside a form keeps its fields in that form: arequiredor invalid field in the closed dialog silently blocks the page form's submit (3.3.1). Render the Dialog outside the form, or render its own<form>conditionally. - Don't move a popup out of the dialog's DOM. A Popover or Dialog opened inside it must stay in its subtree, or it is inert.
- Everything in
button.a11y.mdapplies to the trigger and the Close button.
Warning: Don't forget
Give the dialog a title. Without a name a screen reader says only “dialog”, and the person can’t tell what it is for (4.1.2 Name, Role, Value). Say what each button does, with a verb and an object, never “OK” or “Yes”.
Visual and modes#
- Focus indicator: the trigger, Close and the actions are Buttons and show the standard focus ring, at least 2px thick with at least 3:1 contrast against its background (2.4.7 Focus Visible (AA); the default theme also meets 2.4.13 Focus Appearance (AAA)). The Title shows the same ring after a keyboard open.
- Target size: Close and the actions are never smaller than 24 by 24 CSS pixels, and larger in the default density (2.5.8 Target Size (Minimum) (AA)).
- Colour: the dialog's text keeps at least 4.5:1 contrast on its surface (1.4.3 Contrast (Minimum) (AA)). The edge is decorative, not a control boundary, so 1.4.11 Non-text Contrast (AA) asks nothing of it. The backdrop only dims.
- forced-colors behaviour: the dialog keeps a visible edge on all sides, in the system's text colour. Open state is never shown by colour alone.
- reduced-motion behaviour: opening fades in only without
prefers-reduced-motion: reduce. Closing is always instant, so focus returns at once. - Reflow: on narrow screens the dialog is a sheet at the bottom, as wide as the screen, with no fixed width or height, and scrolls inside when it is too tall. No horizontal scrolling at 320 CSS px (1.4.10 Reflow, AA): the reflow sweep runs every story at 320 CSS px and fails on horizontal overflow.
- 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. Close sits at the inline end and the actions start at the inline start.
Information: Did you know?
While a dialog is open, the page has data-kv-scroll-locked. The default theme turns it into no scrolling. Without the theme, add that rule yourself, or the page behind the dialog scrolls.
Focus management#
- Initial focus:
initialFocusRefif given, else the first tabbable element that is not a Close (any number ofDialog.Closeparts are skipped), else the Title (tabindex="-1"), so a dialog that is mostly reading starts at its beginning and the arrow keys scroll it. Never a Close button and never the popup itself. The browser's own choice is replaced: engines differ. - Trap: native. The page behind is
inert, so Tab cannot reach it. Tab leaves to browser UI before wrapping (approved deviation above), so there is no keyboard trap (2.1.2). - Restore to, in order:
finalFocusRef, the Trigger if it is still in the document, the element that had focus before the dialog opened if it is still in the document, and last the invoker ([aria-controls]) of the popup that element was in (a Menu item that opened the dialog, once the menu has hidden). Each only if it takes focus. Neverbody: when none does, a development warning names the problem, and the consumer passesfinalFocusRefor renders a Trigger. Focus is returned only when it was inside the dialog, or lost tobodyafter it had been inside (or the dialog had an opener): a dialog closed before focus ever entered it, with nothing focused when it opened, leaves focus alone. Focus the consumer moved elsewhere is kept. - Never obscured by: nothing inside is sticky or pinned, and a long dialog scrolls inside the popup (2.4.11). A consumer with a sticky header on a page keeps
scroll-paddingfor the trigger.
Information: Did you know?
A dialog adds no announcement of its own. Opening it moves focus in, and a screen reader then reads the dialog’s role, its name (the Title) and its description. Write a Title and a Description that make sense when read alone, and listen to them with your own screen reader users.
WCAG success criteria#
- 1.3.1 Info and Relationships (A), 4.1.2 Name, Role, Value (A): the role,
aria-modal, the name from the Title and the description. - 1.3.2 Meaningful Sequence (A), 2.4.3 Focus Order (A): Close after the Title, the actions in DOM order, focus in on open and back on close.
- 1.4.3 Contrast (Minimum) (AA): the dialog's text on its surface.
- 1.4.10 Reflow (AA), 1.4.4 Resize Text (AA): the sheet and the inside scroll.
- 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), 2.1.4 Character Key Shortcuts (A): native button keys and Escape. No shortcuts. Tab leaves to browser UI.
- 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA): nothing pinned.
- 2.5.8 Target Size (Minimum) (AA): the buttons are never smaller than 24 by 24 CSS pixels.
- 3.2.1 On Focus (A), 3.2.2 On Input (A): opening needs a press, and typing never moves focus.
- 4.1.3 Status Messages (AA): the dialog's own live regions.
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: dialog.test.tsx › Tab focuses the trigger, and is one stop |
| Shift+Tab | on the trigger | Moves focus to the previous focusable element Test: dialog.test.tsx › Shift+Tab leaves the trigger backwards |
| Enter / Space | on the trigger | Opens the dialog. Focus moves to initialFocusRef, else the first tabbable that is not Close, else the titleTest: dialog.test.tsx › Enter and Space on the trigger open the dialog, dialog.test.tsx › opening moves focus to initialFocusRef, dialog.test.tsx › opening moves focus to the first tabbable that is not Close |
| Tab / Shift+Tab | inside the dialog | Moves to the next or previous tabbable element inside, in DOM order. At either end focus leaves to the browser's own UI and wraps (native; the approved deviation) Test: dialog.test.tsx › Tab and Shift+Tab move between the tabbable elements inside, in DOM order |
| Tab / Shift+Tab | any | The page behind the dialog is never reached: it is inertTest: dialog.test.tsx › Tab and Shift+Tab never reach the page behind the dialog |
| Escape | inside the dialog, no other layer open | Closes the dialog with reason escape and returns focus. A controlled owner can refuseTest: dialog.test.tsx › Escape closes the dialog and returns focus to the trigger, dialog.test.tsx › a controlled owner that refuses keeps the dialog open after Escape |
| Escape | a Popover, Listbox or Combobox open inside the dialog | Closes that layer only. The next Escape closes the dialog Test: dialog.test.tsx › Escape closes a Popover inside first, then the dialog |
| Escape | nested dialogs | Closes the innermost only. Focus returns to the trigger that opened it Test: dialog.test.tsx › Escape closes the innermost of nested dialogs only |
| Enter / Space | on Close | Closes the dialog with reason close-press and returns focusTest: dialog.test.tsx › Enter and Space on Close close the dialog with reason close-press, and focus returns |
| Enter | in a text field in a form | Native: submits the form. The dialog does not take the key Test: dialog.test.tsx › Enter in a text field submits the form and is not taken |
| Pointer press | on the backdrop, with dismissOnOutsidePress | Closes the dialog with reason outside-press. A touch press counts when the finger liftsTest: dialog.test.tsx › a press on the backdrop closes the dialog with dismissOnOutsidePress, and touch counts when the finger lifts |
| Pointer press | on the backdrop, by default | Nothing: a stray tap or a tremor must not lose what someone typed Test: dialog.test.tsx › a press on the backdrop does nothing by default |
| Pointer press | inside the dialog | Nothing Test: dialog.test.tsx › a press inside the dialog does nothing |
The dialog handles no other key. Arrow keys, Home, End, Page Up and Page Down are the content's own (a field, a list, native scrolling of a long dialog), and the component prevents none of them. Escape is read on the document, after the page's handlers: a handler that calls preventDefault() on it keeps the dialog open.
API reference#
import { Dialog, useDialog } from '@kvirn-ui/react'Dialog.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. The default theme is described on Theming.
| 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. |
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 dialog stays. details.reason is trigger-press, close-press, escape, outside-press or native-close (the browser closed it, for example a form with method="dialog"), and details.event is the native event. |
initialFocusRef | RefObject<HTMLElement | null> | – | Where focus goes when it opens. Default: the first tabbable element that is not Close, else the title. |
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. |
messages | Partial<KvirnMessages["dialog"]> | – | Overrides for this dialog’s strings: close, the name of an icon-only Close. |
dismissOnOutsidePress | boolean | false | Whether a press on the backdrop closes it, with reason outside-press. Off by default, so a stray tap or a tremor never loses what someone typed. Turn it on for a read-only dialog. |
children | ReactNode | – | The Trigger and the Popup. Root renders no element. |
Dialog.Trigger
Renders <button type="button">, optional. It takes every attribute of a <button> and passes ref to it. Focus returns here when the dialog closes.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog-trigger | always | The part class. |
aria-haspopup | "dialog" | The trigger opens a dialog. |
data-open | present or absent | The dialog is open. |
Dialog.Popup
Renders <dialog> shown with showModal(). The browser puts it in the top layer, above all other content, so it needs no portal or z-index. Its children stay in the page while it is closed, hidden and out of reach, so what was typed is kept.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-dialog | always | The part class. |
role | "dialog" | A modal dialog, shown with showModal(). The page behind it is inert: the keyboard, the pointer and screen readers can’t reach it. |
aria-modal | "true" while open | The page behind the dialog is inert. |
aria-labelledby | the title’s id | Present while a Title is rendered. Without a Title, name it with aria-label. |
aria-describedby | the description’s id | Present while a Description is rendered. |
data-open | present or absent | The dialog is open. |
data-kv-scroll-locked | present or absent, on <html> | Set while any dialog is open, counted across nested dialogs. The default theme turns it into overflow: hidden. Without the theme, add that CSS yourself. |
Dialog.Title
Renders <h2> that names the dialog.
| 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 | always | The part class. |
tabindex | "-1" | Focus lands here when nothing tabbable comes first, so a long read starts at the top. |
Dialog.Description
Renders <p> with a short explanation. It describes the dialog to a screen reader (software that reads the screen aloud).
| 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 | always | The part class. |
Dialog.Body
Renders <div> for the 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 | always | The part class. |
Dialog.Actions
Renders <div> for the 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 | always | The part class. |
Dialog.Close
Renders <button type="button"> that closes the dialog with the reason close-press. With no children it is an icon button named by the dialog.close message. With children, they are its name. Put the icon button after the Title.
| Prop | Type | Default | Description |
|---|---|---|---|
messages | Partial<KvirnMessages["dialog"]> | – | Overrides for this button’s name: close. Used only when it has no children. Without children it is an icon button named by the message. |
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-dialog-close | always | The part class. |
aria-label | the dialog.close message | Only when it has no children. |
useDialog
The hook does not host the live regions that Dialog.Root adds, because the provider’s are inert while a modal is open. Render your own 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. |
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 dialog stays. details.reason is trigger-press, close-press, escape, outside-press or native-close (the browser closed it, for example a form with method="dialog"), and details.event is the native event. |
initialFocusRef | RefObject<HTMLElement | null> | – | Where focus goes when it opens. Default: the first tabbable element that is not Close, else the title. |
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. |
messages | Partial<KvirnMessages["dialog"]> | – | Overrides for this dialog’s strings: close, the name of an icon-only Close. |
dismissOnOutsidePress | boolean | false | Whether a press on the backdrop closes it, with reason outside-press. Off by default, so a stray tap or a tremor never loses what someone typed. Turn it on for a read-only dialog. |
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. |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one Dialog, pass its messages prop.
dialog.close
The name of a Dialog.Close that has no text, only the icon. A Close with text is named by that text.
| Language | Default text |
|---|---|
| Svenska | Stäng dialogrutan |
| Suomi | Sulje dialogi |
| Norsk bokmål | Lukk dialogvinduet |
| Norsk nynorsk | Lukk dialogvindauget |
| English | Close dialog |
Known issues#
- Tab leaves to browser UI before it wraps (approved deviation). A user who expects the APG cycle needs one more Tab.
- The own live region exists only while open, so a message in the first moments may be missed. Test it with your own screen reader users.
- Tested in Chromium only.
showModal()focus differs between engines, so an effect sets focus explicitly. Check Safari 17 and iOS with your own users. - A closed dialog's content is in the DOM (hidden and inert, with its ids from the first render, which must be unique on the page). A dialog that unmounts while open does not return focus: the trigger usually goes with it.
aria-labelledbyandaria-describedbyappear after the first client render because the parts register in effects. On the server, the markup has neither.
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 | dialog.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | dialog.test.tsx (axe and role, name and state): an open dialog is modal, has role dialog, aria-modal and data-open, and no axe violations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 13 rows, each names a test in dialog.test.tsx |
| Focus order and management | pass | n/a | pass | dialog.test.tsx: the title is an h2 that takes focus programmatically but is never a Tab stop |
| 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 the dialog's own live region is announced when a message arrives in the first moments after opening (it exists only while open), whether the focus move reads the name and description on every screen reader, and a second Escape without a user gesture on Safari 17 and Chromium (the close handler and the re-show cover it).
What to check#
With a screen reader and the keyboard, try:
- Open with Enter, then with Space: focus lands on the first control that is not Close.
- Tab never reaches the page behind the dialog.
- Escape closes the dialog and focus returns to the trigger.
- Type some text, press Escape and open the dialog again: the text is still there.
- With
dismissOnOutsidePressoff, a tap on the backdrop does nothing.