Q40: How do you build an accessible Focus Trap component using refs and custom hooks?

Focus trapping traps keyboard Tab navigation within active modal dialogs. Implemented by capturing focusable DOM elements (button, [href], input, select, textarea) inside a useRef container and wrapping keydown events to cycle focus between first and last elements.

Modal Focus Trap Event Handling
function handleKeyDown(e) {
  if (e.key !== 'Tab') return;
  const focusables = modalRef.current.querySelectorAll('button, input, [href]');
  const first = focusables[0];
  const last = focusables[focusables.length - 1];

  if (e.shiftKey && document.activeElement === first) {
    last.focus(); e.preventDefault();
  } else if (!e.shiftKey && document.activeElement === last) {
    first.focus(); e.preventDefault();
  }
}
💡 Cycles Tab key focus between boundary elements inside the active modal overlay.
Key Takeaways
  • Traps Tab and Shift+Tab key navigation inside modal boundaries.
  • Crucial requirement for accessible WCAG modal dialog compliance.
Knowledge Check

Why is Focus Trapping required inside web modal dialogs?