React › Accessibility (a11y) in React
How would you manage focus properly in a React modal to keep it accessible?
AdvancedAnswer
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.