Modal Component

ReactModal Component25 mins

by Pratik Rai

Read the full write-up

Build a modal dialog: a button opens it, and it can be dismissed three ways — the Cancel and Confirm buttons, a click on the backdrop, and the Escape key.

The styling and the open/close state are done. The dismissal behaviour is not.

Requirements

  1. Clicking the dark backdrop closes the modal.

  2. Clicking anywhere inside the white dialog does not close it.

  3. Pressing Escape closes the modal, from wherever focus happens to be.

  4. The Escape listener is removed when the modal closes, not left on the document.

  5. The dialog is labelled by its heading (aria-labelledby) and receives focus when it opens.

Notes

  • Rendering the modal into a portal is the usual production answer, but the preview has one root and no stacking-context problem, so it is out of scope here.

  • A full focus trap is a good follow-up question and is deliberately not required.

Hints

Loading editor…