Advertisement
Advanced React, Accessibility (a11y) in React

How would you manage focus properly in a React modal to keep it accessible?

Short answer

When a modal opens, focus should move into the modal automatically, and it should stay trapped inside the modal while it is open so a keyboard user cannot accidentally tab to content behind it. When the modal closes, focus should return to the element that opened it.

Save React mock interview
Advertisement
AModel answer
When a modal opens, focus should move into the modal automatically, and it should stay trapped inside the modal while it is open so a keyboard user cannot accidentally tab to content behind it. When the modal closes, focus should return to the element that opened it.
function Modal({ isOpen, onClose, children }) {
  const modalRef = useRef(null);
  useEffect(() => {
    if (isOpen) modalRef.current?.focus();
  }, [isOpen]);

  if (!isOpen) return null;
  return (
    <div ref={modalRef} tabIndex={-1} role="dialog" aria-modal="true">
      {children}
      <button onClick={onClose}>Close</button>
    </div>
  );
}
Real-world example
A checkout page traps keyboard focus inside its payment confirmation modal so a user pressing Tab repeatedly stays inside the dialog instead of jumping back to the page behind it.
Likely follow-ups
  • How would you build a full focus trap that also cycles back to the first element after the last one?
  • What role and aria attributes are expected on a modal dialog?
Related topics