Home
← All questions

Accessible modal with focus trap | Frontend Machine Coding

HardPremiumMachine Coding

Asked at Meta · Google · Microsoft

Frontend Machine Coding interview practice: Build a modal dialog with focus trap, Escape close, and scroll lock

Problem

Build a modal dialog component meeting WCAG dialog patterns.

Requirements

  • Open/close via prop; render in a Portal.
  • Focus trap — Tab cycles within modal only.
  • Move focus to first focusable on open; restore focus to trigger on close.
  • Close on Escape and overlay click (configurable).
  • Lock body scroll while open.
  • role="dialog", aria-modal="true", labelled by title.

Hints / Approach

  • Query focusable elements: button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"]).
  • Keydown on dialog: intercept Tab at first/last element.
  • Save document.activeElement before open.
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium