Modal Popup
Build a reusable modal dialog component. A button triggers it to open; it can be closed via the backdrop, a close button, or the Escape key.
Requirements
- A button opens the modal overlay
- Modal has a header (title + close button) and body content
- Clicking the dark backdrop closes the modal
- Pressing Escape closes the modal
- Background scroll is locked while modal is open
- Build a confirmation modal variant (Cancel + Confirm buttons)
- Modal is reusable — accepts title and children as props
Key Patterns
isOpen: boolean stateuseEffect for Escape key listener + scroll lockonClick backdrop: e.target === e.currentTarget checkConditional render: if (!isOpen) return nullFixed overlay with flexbox centering
Important
Interview Tip
Two key patterns: (1) Backdrop click — use onClick on the overlay div, check if e.target === e.currentTarget so clicks on the dialog content don't bubble and close it. (2) Escape key — add a keydown listener in useEffect, check e.key === 'Escape', and ALWAYS clean up the listener in the return function. Set document.body.style.overflow = 'hidden' when open to prevent background scroll.