Back to results for “Refs”
React › Accessibility (a11y) in React

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

Advanced

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.

Common 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?