Sub topic 8
Accessibility: roles, focus and Escape
This chapter assumes you can write function components with useState and useEffect, and that you have already built the basic portal modal from the previous chapter. A portal puts the dialog in the right place visually. It does nothing for keyboard users or screen readers. This chapter covers three things a modal needs: the right roles, managed focus, and a way to close with Escape.
Why portals need extra work
A portal moves DOM nodes to document.body. The browser's tab order follows the DOM, not the React tree. Two problems follow:
- Focus stays on the button that opened the modal, which now sits far from the dialog in the DOM. Pressing Tab moves through the page behind the dialog.
- Screen readers still read the page behind the dialog as available content.
The modal must fix both.
Roles and labels
The dialog element needs role="dialog" and aria-modal="true". It also needs an accessible name, which a screen reader announces when the dialog opens. Use aria-labelledby to point at the visible heading.
import { createPortal } from 'react-dom';
function Modal({ title, children, onClose }) {
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
onClick={(e) => e.stopPropagation()}
>
<h2 id="modal-title">{title}</h2>
{children}
</div>
</div>,
document.body
);
}The fixed id modal-title breaks if two modals are open at once. Generate the id with useId in that case.
Moving focus into the dialog
When the modal opens, move focus inside it. When it closes, return focus to the element that opened it. Give the dialog tabIndex={-1} so it can receive focus from code without joining the Tab order.
import { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
function FocusModal({ title, children, onClose }) {
const dialogRef = useRef(null);
useEffect(() => {
const previouslyFocused = document.activeElement;
dialogRef.current.focus();
return () => {
if (previouslyFocused instanceof HTMLElement) {
previouslyFocused.focus();
}
};
}, []);
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
ref={dialogRef}
tabIndex={-1}
className="dialog"
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
onClick={(e) => e.stopPropagation()}
>
<h2 id="modal-title">{title}</h2>
{children}
</div>
</div>,
document.body
);
}The effect reads document.activeElement before moving focus. Its cleanup runs when the modal unmounts, which restores focus to the trigger.
Closing with Escape
Keyboard users expect Escape to close a dialog. A listener on document catches the key no matter which element has focus. The hook below adds the listener and removes it on cleanup, so no stray listeners remain after the modal closes.
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]);
}Call it inside the modal: useEscapeKey(onClose). If the parent passes a new onClose function on every render, the effect re-subscribes each time. That is harmless but wasteful. Wrap the handler in useCallback in the parent to avoid it.
What `aria-modal` does not do
aria-modal="true" tells assistive technology to treat content outside the dialog as inert. Support varies between browsers and screen readers. It does not stop Tab from leaving the dialog. Two options cover the gap:
- Trap focus yourself. On Tab from the last focusable element, move to the first, and the reverse for Shift+Tab.
- Mark the rest of the page inert. The
inertattribute on the app root makes everything inside it unfocusable and hidden from assistive technology. Render the portal outside that root, such as indocument.bodynext to it.
The second option fits portals well, because the portal content is already a sibling of the app root.
Quick checklist
| Requirement | How |
|---|---|
| Announced as a dialog | `role="dialog"` and `aria-modal="true"` |
| Has a name | `aria-labelledby` pointing at the heading |
| Focus enters on open | `ref.focus()` in an effect |
| Focus returns on close | Save `document.activeElement`, restore in cleanup |
| Escape closes | `keydown` listener on `document`, removed on cleanup |
| Tab stays inside | Focus trap or `inert` on the rest of the page |
Exercise
A modal opens and focus moves into it correctly. After the user presses Escape, the modal closes but keyboard focus is lost and starts again from the top of the page. What is missing, and where should the fix go?
Show answer
The modal never restores focus to the element that opened it. Save document.activeElement in the effect that runs on mount, before moving focus into the dialog. Call .focus() on that saved element in the effect's cleanup function, which runs when the modal unmounts.
Exercise
Why does aria-modal="true" alone not make a portal modal fully keyboard-safe?
Show answer
It only signals to assistive technology that the background is inert, and support is inconsistent. It does not prevent Tab from moving focus to elements behind the dialog. You still need a focus trap or the inert attribute on the rest of the page.