Forms & Events — Intermediate React challenge.
Build a Modal with a real keyboard focus trap — not just auto-focus. Tab and Shift+Tab cycle focus between only the modal's own elements, Escape and backdrop clicks close it, and focus is restored to whatever opened it once it closes. (Focus-tracking behavior is graded manually/visually — the automated tests below cover open/close, overlay, and CSS.)
Requirements
- Renders nothing when open is false; when open, renders a dimmed full-screen overlay containing the modal card, an input, and a Close button.
- The input is automatically focused when the modal opens, via useRef + useEffect (not autoFocus).
- Tab on the last focusable element wraps focus back to the first (the input); Shift+Tab on the first wraps to the last — Tab should never escape the modal.
- Clicking the overlay (not the card itself) closes the modal; clicking inside the card does not.
- Pressing Escape closes the modal.
- When the modal closes, focus is restored to triggerRef.current.
- The overlay and modal card carry specific inline CSS (dimmed backdrop, white rounded card) — this part IS covered by the automated tests.
Signature
function Modal({
open: boolean;
onClose: () => void;
triggerRef: React.RefObject<HTMLElement>;
}): JSX.Element | nullExample
<Modal open={open} onClose={() => setOpen(false)} triggerRef={triggerRef} />
// opens -> input auto-focused
// Tab from Close button -> wraps back to input
// Escape or backdrop click -> closes, focus returns to the trigger buttonConstraints
- Use useRef + useEffect for focus behavior — do not use autoFocus.
- Do not let Tab/Shift+Tab move focus to anything outside the modal while it's open.