Sub topic 8
Accessibility: roles, focus and Escape
A modal built with a portal looks right on screen, but a screen reader user or a keyboard user may still be stuck. This chapter covers what a portal does not do for you: announcing the dialog, moving focus into it, keeping focus inside, closing on Escape, and returning focus afterward.
Prerequisites
This chapter assumes you can write function components, use useState, useEffect and useRef, and that you have read the earlier chapters on createPortal and the modal pattern. You should know that a portal changes where nodes appear in the DOM, not where they sit in the React tree.
What a portal does not give you
createPortal only moves DOM nodes. It adds no semantics and no focus behavior. Three things are your job:
- Semantics. Assistive technology needs to know the content is a dialog.
- Focus. Keyboard focus must move into the dialog when it opens, stay there while it is open, and go back to where it came from when it closes.
- Dismissal. Keyboard users expect Escape to close the dialog.
There is also a side effect of portaling to document.body. The dialog becomes a sibling of your app root in the DOM. The rest of the page stays reachable by Tab and by screen reader navigation unless you prevent it.
Roles and labels
The Modal from the previous chapter already sets role="dialog" and aria-modal="true". Here is what each does.
role="dialog"tells assistive technology that this element is a dialog window. Userole="alertdialog"when the dialog interrupts the user with an urgent message that needs a response.aria-modal="true"tells assistive technology that content outside the dialog is inert while it is open. Support varies, so do not rely on it alone to block the rest of the page.aria-labelledbypoints to the id of the visible title. A dialog needs an accessible name, or a screen reader announces only "dialog".aria-describedbyoptionally points to descriptive text.
Use useId so that ids stay unique when several modals exist and are stable between server and client.
import { useId } from 'react';
import { createPortal } from 'react-dom';
function Modal({ title, children, onClose }) {
const titleId = useId();
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
onClick={(e) => e.stopPropagation()}
>
<h2 id={titleId}>{title}</h2>
{children}
<button type="button" onClick={onClose}>Close</button>
</div>
</div>,
document.body
);
}The explicit Close button matters. Not every user can press Escape or click a backdrop, and a visible button is the most discoverable way out.
Closing on Escape
Escape handling belongs on document, not on the dialog element. If focus is on the dialog, a handler on the dialog works. If focus has drifted to document.body, for example after the user clicks on non-focusable text, only a document-level listener still fires.
import { useEffect } from 'react';
function useEscapeKey(onEscape) {
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') onEscape();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [onEscape]);
}The cleanup function removes the listener when the modal unmounts. Without it, every open and close would leave another listener behind, and a closed modal's handler would still run.
The dependency [onEscape] has a trap. If the parent passes a new inline function on every render, the effect re-subscribes on every render. This is correct but wasteful. If you want a stable subscription, keep the latest callback in a ref:
import { useEffect, useRef } from 'react';
function useEscapeKey(onEscape) {
const handlerRef = useRef(onEscape);
useEffect(() => {
handlerRef.current = onEscape;
});
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') handlerRef.current();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, []);
}Stacked dialogs
If a dialog can open another dialog, one Escape press would close both, because both have document listeners. The simplest fix is to call event.stopPropagation() in a listener on the dialog element itself, so the dialog handles Escape before it reaches document. A more scalable fix is a small stack that tracks which modal is topmost, and lets only that modal respond.
Moving focus into the dialog
When the modal opens, focus must move into it. Otherwise a keyboard user stays on the trigger button behind the backdrop, and a screen reader may keep reading the page underneath.
The usual approach is to give the dialog container tabIndex={-1}. This makes it focusable from code, but keeps it out of the Tab order. Then focus it in an effect.
import { useEffect, useRef, useId } from 'react';
import { createPortal } from 'react-dom';
function Modal({ title, children, onClose }) {
const titleId = useId();
const dialogRef = useRef(null);
useEffect(() => {
dialogRef.current.focus();
}, []);
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
ref={dialogRef}
tabIndex={-1}
className="dialog"
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
onClick={(e) => e.stopPropagation()}
>
<h2 id={titleId}>{title}</h2>
{children}
<button type="button" onClick={onClose}>Close</button>
</div>
</div>,
document.body
);
}Focusing the container is a safe default. For a form dialog, focus the first input instead. For a destructive confirmation, focus the least harmful button, usually Cancel, so that a reflexive Enter press does not delete anything.
Restoring focus on close
When the modal closes, return focus to the element that opened it. If you skip this, focus falls back to document.body, and a keyboard user must tab through the whole page again.
Capture document.activeElement before the modal takes focus, then restore it in the cleanup.
useEffect(() => {
const previouslyFocused = document.activeElement;
dialogRef.current.focus();
return () => {
if (previouslyFocused instanceof HTMLElement) {
previouslyFocused.focus();
}
};
}, []);The instanceof check guards against activeElement being null or an SVG element without a focus method in some browsers. If the trigger was removed from the DOM while the modal was open, focus() does nothing and focus falls back to the body. Handle that case if your trigger can disappear, for example by focusing a nearby heading.
Trapping focus
Moving focus in is not enough. When the user presses Tab on the last control, the browser moves focus to the next focusable element in the DOM. Because the portal sits at the end of document.body, that is the browser's own UI, and Shift+Tab from the first control leaves the dialog backward into the page content. A focus trap keeps focus cycling inside the dialog.
This handler wraps Tab at both ends:
const FOCUSABLE =
'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
function trapTab(event, container) {
if (event.key !== 'Tab') return;
const items = container.querySelectorAll(FOCUSABLE);
if (items.length === 0) {
event.preventDefault();
return;
}
const first = items[0];
const last = items[items.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}Attach it with onKeyDown={(e) => trapTab(e, dialogRef.current)} on the dialog element. One gotcha: when the dialog container itself has focus (as after the earlier effect), Shift+Tab is not caught by the first check. Add a condition for document.activeElement === container in the Shift+Tab branch if you use this approach.
This is a simplified trap. It does not handle hidden elements, inert subtrees, radio groups or shadow DOM. For production use, prefer a tested library such as focus-trap-react or a headless component library such as Radix UI or React Aria, which handle those cases.
Making the background inert
A focus trap handles keyboard users. Screen reader users can still browse the page behind the dialog with virtual cursor commands, since aria-modal support is uneven. The inert attribute is the most direct fix. An inert element cannot be focused or clicked, and is hidden from the accessibility tree.
Because the portal renders into document.body as a sibling of your app root, you can mark the root inert while the modal is open:
useEffect(() => {
const root = document.getElementById('root');
root.setAttribute('inert', '');
return () => root.removeAttribute('inert');
}, []);This only works because the dialog is outside #root. It is a good reason to portal to document.body or a dedicated sibling container rather than a node inside the app root. Check browser support for inert against your target list before you depend on it. With inert in place, many of the focus-trap edge cases disappear, because the browser itself refuses to focus anything outside the dialog.
You should also lock page scroll while the modal is open, usually by setting document.body.style.overflow = 'hidden' and restoring the previous value in cleanup.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| No `aria-labelledby` or `aria-label` | Screen reader announces an unnamed dialog | Link the title with `useId` |
| Focus stays on the trigger | Keyboard users type into the page behind the backdrop | Focus the dialog in an effect |
| Focus not restored on close | Focus is lost to `body` | Save and restore `activeElement` |
| Escape listener without cleanup | Handlers pile up and fire after close | Return a cleanup that removes the listener |
| Backdrop click closes the dialog even when the click starts inside it | Dragging a text selection out of the dialog closes it | Close on `mousedown` target check, or compare `event.target` with `event.currentTarget` |
| Nested modals share one Escape handler | One key press closes all of them | Track a stack of open modals |
Checking your work
Automated tests catch some of this. Using Testing Library, you can assert the accessible name and the focus target:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('labels the dialog, focuses it, and closes on Escape', async () => {
const onClose = jest.fn();
render(<Modal title="Settings" onClose={onClose}>Body</Modal>);
const dialog = screen.getByRole('dialog', { name: 'Settings' });
expect(dialog).toHaveFocus();
await userEvent.keyboard('{Escape}');
expect(onClose).toHaveBeenCalled();
});This works only if the modal calls useEscapeKey(onClose). Add that line to the component first. Tests do not replace a manual pass: open the dialog with the keyboard only, press Tab through every control, press Escape, and confirm focus lands back on the trigger. Then repeat with a screen reader such as NVDA, VoiceOver or Orca.
Exercise
A modal portals into document.body and has role="dialog" and aria-modal="true". A keyboard user opens it from a button, presses Tab several times, and ends up on links in the page behind the backdrop. Name two separate fixes and say what each one changes.
Show answer
First, add a focus trap: a keydown handler (or a library such as focus-trap-react) that wraps Tab from the last focusable element to the first and Shift+Tab from the first to the last, so focus cannot leave the dialog. Second, mark the app root inert with setAttribute('inert', '') while the modal is open (removing it in the effect cleanup). This stops the browser from focusing or clicking anything in the page and hides it from screen readers. aria-modal alone does not block keyboard focus.
Exercise
Your modal closes on Escape, but after it closes, keyboard focus is at the top of the page. Which two steps are missing, and where should they go in the component?
Show answer
Save document.activeElement before moving focus into the dialog, and call focus() on that saved element. Both belong in the same useEffect: the save and the initial focus() run in the effect body, and the restore goes in the returned cleanup function, which runs when the modal unmounts.