“Build a modal dialog in React. What makes it accessible?” The trap in this question is that a modal can look finished and still be unusable: keyboard users tab into the page behind it, screen reader users never learn that it opened, and closing it drops focus at the top of the document.
A complete answer lists the behaviours a modal must have and then shows how to get them, starting with the native <dialog> element instead of rebuilding everything with divs. The code below assumes you know refs, effects and aria-labelledby, runs on React 18 and 19, and treats the ARIA Authoring Practices modal dialog pattern as the reference for expected behaviour.
Six things an accessible modal must do
An accessible modal must: move focus into the dialog when it opens; keep Tab and Shift+Tab inside it while open; make the rest of the page inert to pointer, keyboard and screen readers; close on Escape; have an accessible name; and return focus to the element that opened it when it closes. The native <dialog> element opened with showModal() provides containment, inertness of the background, Escape handling and top-layer rendering. In React you mainly need to call showModal() and close() from an effect, sync the close event back into state, label the dialog, and restore focus.
What showModal() handles for you
showModal() places the dialog in the browser’s top layer, above everything regardless of z-index, and makes the rest of the document inert. The browser moves focus into the dialog, and pressing Escape fires a cancel event followed by close.
import { useEffect, useId, useRef } from 'react';
export function Modal({ open, onClose, title, children }) {
const ref = useRef(null);
const titleId = useId();
useEffect(() => {
const dialog = ref.current;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
return (
<dialog ref={ref} aria-labelledby={titleId} onClose={onClose}>
<h2 id={titleId}>{title}</h2>
{children}
<button type="button" onClick={onClose}>Close</button>
</dialog>
);
}React owns the open state; the effect translates it into the imperative showModal() and close() calls. When the user presses Escape, the browser closes the dialog and fires close, and onClose updates the parent’s state so React and the DOM agree again. Do not set the open attribute directly as a prop, because that opens the dialog non-modally, without inertness or Escape handling.
The parts the browser leaves to you
An accessible name and a safe first focus
aria-labelledby pointing to the heading lets screen readers announce “Delete project, dialog” when it opens. showModal() focuses the element carrying the autofocus attribute, or else the first focusable element inside the dialog. React’s autoFocus prop doesn’t help here: React doesn’t write the attribute to the DOM, it calls focus() when the element mounts, and this dialog’s children mount while the dialog is still closed. For destructive confirmations, put the safest button, typically “Cancel”, first in DOM order so it receives focus and Enter does not delete by accident, or call focus() on it in the effect right after showModal().
Returning focus to the button that opened it
Browsers now restore focus to the previously focused element when a modal dialog closes, but behaviour has varied across versions, and when the trigger unmounts it fails. Capture the trigger explicitly:
useEffect(() => {
if (!open) return;
const trigger = document.activeElement;
return () => {
if (trigger instanceof HTMLElement && trigger.isConnected) trigger.focus();
};
}, [open]);Declare this effect above the showModal() effect. Effects run in the order they are declared, and showModal() moves focus into the dialog synchronously, so a copy declared below it captures the dialog’s first button instead of the trigger. When open becomes false, the cleanup runs and focus goes back to the button that opened the dialog. If that button was removed (say, the row was deleted), move focus to a logical place such as the list heading.
Deciding what a backdrop click does
Clicking the backdrop of a native dialog targets the <dialog> element itself. If closing on backdrop click is desired:
<dialog
ref={ref}
onClick={e => { if (e.target === e.currentTarget) onClose(); }}
>
<div className="dialog-body">{/* content */}</div>
</dialog>Wrap content in an inner element with padding so clicks inside never target the dialog. For forms with unsaved data, consider not closing on backdrop click, or confirm first.
Keeping Escape from discarding a half-filled form
If the dialog holds a half-filled form, intercept cancel:
<dialog onCancel={e => { if (isDirty) { e.preventDefault(); askToDiscard(); } }} />Use this sparingly; Escape should usually close.
What a div modal has to rebuild by hand
If you cannot use <dialog>, you need role="dialog", aria-modal="true", a portal to the end of body, a focus trap that cycles Tab, the inert attribute on the app root, Escape handling and scroll locking. That is a lot to get right, which is why the native element or a tested library (Radix, React Aria, Headless UI) is usually the better answer. See portals and event bubbling for the portal details.
Mistakes that look fine on screen
- “It has a dark overlay, so it is modal.” Visual overlays do not stop keyboard focus or screen reader navigation.
- Rendering
<dialog open>. That shows a non-modal dialog without inertness or Escape handling. CallshowModal(). - Not syncing the close event. If Escape closes the dialog but React state still says
open, the next click on the trigger does nothing because the effect sees no change. - Forgetting focus restoration. Users lose their place after every dialog.
- Using
aria-hiddenon the app root while focus can still reach it. Hidden yet focusable content confuses screen readers; use theinertattribute, or letshowModal()make the background inert for you. - Missing an accessible name. “Dialog” with no title tells users nothing.
Fixing a div-based “Delete project” modal after an audit
Picture a project management app with a custom “Delete project” modal built from a div with a dark overlay. An accessibility audit finds four issues: keyboard users can Tab to buttons behind the overlay, screen readers do not announce the dialog, Escape does nothing, and after closing, focus goes to the top of the page so keyboard users have to tab through the whole navigation to get back.
The rewrite uses the Modal component above:
function DeleteProjectButton({ project, onDelete }) {
const [open, setOpen] = useState(false);
return (
<>
<button onClick={() => setOpen(true)}>Delete</button>
<Modal open={open} onClose={() => setOpen(false)} title={`Delete ${project.name}?`}>
<p>This removes all tasks in the project.</p>
<button onClick={() => setOpen(false)}>Cancel</button>
<button onClick={() => { onDelete(project.id); setOpen(false); }}>Delete project</button>
</Modal>
</>
);
}showModal() makes the background inert and handles Escape. aria-labelledby gives the announcement. Cancel comes before “Delete project” in the markup, so showModal() focuses it first and a stray Enter cancels instead of deleting. The focus restoration effect returns users to the Delete button, or to the project list heading when the project is gone. The custom overlay and its z-index battles go away as well.
Testing focus restoration in jsdom and by hand
Test with the keyboard and with React Testing Library. jsdom (checked with version 25) has no showModal() or close() at all, so stub them. Make the showModal stub move focus the way a browser does; a stub that leaves focus alone lets the effect-order bug above pass unnoticed:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
beforeAll(() => {
HTMLDialogElement.prototype.showModal = function () {
this.open = true;
this.querySelector('button, [href], input, select, textarea')?.focus();
};
HTMLDialogElement.prototype.close = function () {
this.open = false;
this.dispatchEvent(new Event('close'));
};
});
test('restores focus to the trigger after closing', async () => {
const user = userEvent.setup();
render(<DeleteProjectButton project={{ id: 1, name: 'Apollo' }} onDelete={() => {}} />);
const trigger = screen.getByRole('button', { name: 'Delete' });
await user.click(trigger);
expect(screen.getByRole('dialog', { name: 'Delete Apollo?' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Cancel' }));
expect(trigger).toHaveFocus();
});Then test manually in a real browser: open with Enter, Tab through every control and confirm focus never leaves, press Escape, and confirm focus is back on the trigger. Repeat with VoiceOver or NVDA to hear the announcement. Automated tests catch regressions; manual checks catch behaviour jsdom cannot simulate, such as true inertness.
Focus vanishes after saving a row: an interview case
A modal opens from a row’s “Edit” button. After saving, the list re-renders, the row moves to the top (sorted by last modified), and focus disappears. What is going on, and how would you fix it?
A strong answer
Focus was meant to return to the trigger, but the trigger either unmounted or was replaced when the list re-sorted, for example because rows are keyed by index or the edit button is conditionally rendered. Focusing a detached element does nothing, so focus falls to body. First, give rows stable keys (key={row.id}) so React moves the existing row and its button instead of recreating them; then restoring focus to the captured element works even after the reorder. Second, add a fallback: if trigger.isConnected is false, focus the row’s new edit button by id or the list heading. Finally, consider announcing “Saved” in a live region so screen reader users get confirmation of what happened.
Follow-ups on live regions, scroll lock and libraries
Should a dialog announce dynamic messages, like a save error? Use a live region inside or near the dialog. See accessibility announcements.
What about scroll locking? Modal dialogs do not stop the page behind them from scrolling by default. Add overflow: hidden on body while open, or let CSS do it with body:has(dialog[open]) { overflow: hidden; }.
When is a non-modal dialog appropriate? For panels the user works alongside, like a find-and-replace box. Use show() instead of showModal() and do not trap focus.
Why not always use a library? Libraries are a good default for complex cases (nested dialogs, animations, older browser support). Knowing the underlying requirements lets you evaluate them and debug them.
More on dialogs, portals and focus
Continue with the React interview questions and the React MCQs. Related notes: portals and event bubbling, accessibility announcements and list keys and identity. Official references: the ARIA modal dialog pattern and the createPortal reference on react.dev.