← Back to React, page 4

react-0077 · Medium mid

How do you build an accessible modal dialog in React that traps focus, closes on Escape and returns focus to the opener?

Render the dialog with role="dialog", aria-modal="true" and a label. When it opens, move focus inside (to the first control or the dialog itself). Handle Tab and Shift+Tab to cycle within the dialog, close on Escape, and on close restore focus to the element that opened it. The native dialog element with showModal() does most of this, so prefer it when you can, and mark the background inert.

Full answer

A modal must stop users from interacting with the page behind it. For keyboard and screen reader users that means four behaviours.

  1. Move focus in. On open, focus the first focusable element or the dialog container (with tabIndex -1). Store document.activeElement before opening, so you can return later.
  2. Trap focus. Tab on the last element goes to the first, and Shift+Tab on the first goes to the last. A keydown handler on the dialog finds the focusable elements with a selector and wraps.
  3. Close with Escape, and also with a visible close button.
  4. Restore focus. On close, focus the element that opened the dialog. Do this in an effect cleanup or after the state change.

Markup: role="dialog" (or "alertdialog"), aria-modal="true", and aria-labelledby pointing at the title. Render through a portal (createPortal to document.body) so stacking and overflow of parents do not interfere. Make the rest of the page inert so it cannot be focused or read while the dialog is open.

The native <dialog> element handles most of this. dialog.showModal() gives you focus management, a focus trap, Escape to close and an inert background. In React, use a ref and call showModal() in an effect when open becomes true. Use the native element when your browser support allows, and keep a library such as Radix Dialog or React Aria when you need more features, because custom traps miss edge cases such as shadow DOM, dynamic content and iframes.

The example implements the manual version to show the logic.

jsx
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';

const FOCUSABLE = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

function Modal({ title, onClose, children }) {
  const dialogRef = useRef(null);

  useEffect(() => {
    const opener = document.activeElement;
    dialogRef.current.querySelector(FOCUSABLE)?.focus();
    return () => opener?.focus();
  }, []);

  function handleKeyDown(event) {
    if (event.key === 'Escape') {
      onClose();
      return;
    }
    if (event.key !== 'Tab') return;
    const items = dialogRef.current.querySelectorAll(FOCUSABLE);
    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();
    }
  }

  return createPortal(
    <div role="dialog" aria-modal="true" aria-labelledby="modal-title" ref={dialogRef} onKeyDown={handleKeyDown}>
      <h2 id="modal-title">{title}</h2>
      {children}
      <button onClick={onClose}>Close</button>
    </div>,
    document.body
  );
}

export default function App() {
  const [open, setOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setOpen(true)}>Open dialog</button>
      {open && (
        <Modal title="Confirm enrollment" onClose={() => setOpen(false)}>
          <input aria-label="Coupon code" />
          <button onClick={() => setOpen(false)}>Enroll</button>
        </Modal>
      )}
    </div>
  );
}

The dialog has three focusable controls: the coupon input, Enroll and Close. jsdom does not move focus on Tab, so the check sent each keydown to the dialog and moved focus itself only when the handler did not cancel the event, as a browser would. Then it pressed Escape. Output of the run: after opening: focus on "Coupon code" Tab: focus on "Enroll" Tab again: focus on "Close" Tab third time wraps: focus on "Coupon code" Shift+Tab goes back to last: focus on "Close" after Escape: focus on "Open dialog" dialog in DOM: false

Key points

  • Move focus into the dialog on open and restore it to the opener on close.
  • Wrap Tab and Shift+Tab inside the dialog, and close on Escape.
  • Use role="dialog", aria-modal and aria-labelledby, and render in a portal.
  • Make the background inert while the dialog is open.
  • Prefer the native dialog element with showModal(), or a trusted library.

Common mistakes

  • Leaving focus on the page behind the dialog.
  • Not restoring focus to the opener on close.
  • Trapping focus with no Escape or close button.
  • Building a custom trap when the native dialog would work.
  • Missing aria-labelledby, so the dialog has no accessible name.

Follow-ups

  • How would the native dialog element simplify this component?
  • What does the inert attribute do and how does it help?
  • How would you handle nested dialogs?

Tips

  • List the four behaviours before coding. Interviewers check for them.
  • Mention the native dialog first, then explain the manual version.
  • Say you would use a tested library in production.