Modal Dialog

MediumReact Components20 min5 tests

Build a modal dialog that opens from a button and can be dismissed. The dialog uses role="dialog", contains a heading and a Close button, and is absent from the document until opened.

Create an App component that renders an "Open" button. When the user clicks "Open", a modal dialog appears. The dialog is an element with role="dialog" (also tagged data-testid="dialog") containing a heading (e.g. "Confirm Action") and a "Close" button. Clicking "Close" removes the dialog from the document entirely.

Requirements:

  • On initial render, NO dialog is present in the document.
  • An accessible "Open" button toggles the dialog open.
  • The open dialog is an element with role="dialog" (and data-testid="dialog") that contains a heading and a "Close" button.
  • Clicking "Close" removes the dialog from the document (it is no longer queryable).
  • The dialog can be re-opened after being closed.

This mirrors a common UI pattern: conditionally rendering an overlay based on a boolean state flag and exposing both an open trigger and a close trigger, while keeping everything keyboard/screen-reader accessible.

Requirements

  • Render an accessible button labeled "Open" that is present on initial render
  • Do NOT render any element with role="dialog" (data-testid="dialog") until the Open button is clicked
  • When Open is clicked, render an element with role="dialog" and data-testid="dialog" containing a heading and a "Close" button
  • When Close is clicked, remove the dialog element from the document so it is no longer queryable
  • Allow the dialog to be opened again after it has been closed
Hints (3)
  1. Use a single boolean state value (useState) to track whether the dialog is open.
  2. Conditionally render the dialog with {open && (...)} so it is fully absent from the DOM when closed — toggling CSS visibility would still leave it queryable.
  3. Give the dialog container role="dialog" and data-testid="dialog"; put the title in a real heading element (h2) and use real <button> elements so getByRole queries can find them by name.

Topics

  • React
  • React Components

Asked at

Rapido · Microsoft · CRED · Dream11 · MakeMyTrip · Zoho

Join Us
blur