Skip to content

Dialogs

The Course
•
20 min study

Widgets people can actually use

Today is about widgets that work for everyone: keyboard users, screen reader users, and people who use both a mouse and a keyboard. A div with an onClick looks like a widget; it isn't one until it can be reached, operated and understood without a mouse.

A modal dialog has a long list of requirements: move focus into it, keep focus inside, block the page behind it, close on Escape, and return focus to the button that opened it. Writing that by hand used to take a library. The browser's <dialog> element now does it all.

Edit a card in a dialog React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Dialog from "./Dialog.jsx"; export default function App() { const [open, setOpen] = useState(false); const [title, setTitle] = useState("Read about Suspense"); return ( <main> <h1>Study Hub</h1> <p className="card">{title}</p> <button onClick={() => setOpen(true)}>Edit card</button>{" "} <button onClick={() => console.log("page button clicked")}>Something on the page</button> <Dialog open={open} onClose={() => setOpen(false)} title="Edit card"> <form method="dialog" onSubmit={(e) => setTitle(new FormData(e.currentTarget).get("title"))}> <p> <label> Title <input name="title" defaultValue={title} /> </label> </p> <div className="toolbar"> <button type="submit">Save</button> <button type="button" onClick={() => setOpen(false)}>Cancel</button> </div> </form> </Dialog> </main> ); } import { useEffect, useRef } from "react"; // The browser's own modal dialog: it moves focus inside, blocks the page // behind it, closes on Escape, and returns focus to whatever opened it. export default function Dialog({ open, onClose, title, children }) { const ref = useRef(null); // Keep the real <dialog> in step with the open prop. useEffect(() => { const dialog = ref.current; if (open && !dialog.open) dialog.showModal(); if (!open && dialog.open) dialog.close(); }, [open]); return ( <dialog ref={ref} onClose={onClose} aria-labelledby="dialog-title"> <h2 id="dialog-title">{title}</h2> {children} </dialog> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Press Edit card and use only the keyboard: Tab around, change the title, press Save. Open it again and press Escape.

What the browser does

dialog.showModal() opens it as a modal:

  • the browser runs its dialog focusing steps; autoFocus can choose the intended initial control, so choose it deliberately;
  • everything outside becomes inert: it can't be clicked, focused or read by a screen reader;
  • Escape closes it and fires its close event;
  • when it closes, focus returns to the element that was focused before it opened.

Driving it from React

React describes what should be on screen; showModal() is a command. The Dialog component bridges the two with an effect:

JavaScript
useEffect(() => {
  const dialog = ref.current;
  if (open && !dialog.open) dialog.showModal();
  if (!open && dialog.open) dialog.close();
}, [open]);

The parent just sets open. When the browser closes the dialog itself, on Escape, onClose tells the parent, so its state stays in step.

aria-labelledby points at the heading, so a screen reader announces the dialog's name when it opens:

JSX
return (
  <dialog ref={ref} onClose={onClose} aria-labelledby="dialog-title">
    <h2 id="dialog-title">{title}</h2>
    {children}
  </dialog>
);

Forms inside

<form method="dialog"> is a form whose submit closes the dialog instead of going anywhere. onSubmit reads the field with FormData before it closes:

JSX
<form method="dialog" onSubmit={(e) => setTitle(new FormData(e.currentTarget).get("title"))}>

Predict

With the dialog open, try to click Something on the page. What happens?

Check your prediction

Nothing: the page behind is inert, so the click doesn't reach the button, and nothing is logged. Clicking the dimmed backdrop doesn't close the dialog either. That's the exercise.

Exercise

Close on a backdrop click

Make a click on the dimmed area outside the dialog close it.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Dialog from "./Dialog.jsx"; export default function App() { const [open, setOpen] = useState(false); const [title, setTitle] = useState("Read about Suspense"); return ( <main> <h1>Study Hub</h1> <p className="card">{title}</p> <button onClick={() => setOpen(true)}>Edit card</button>{" "} <button onClick={() => console.log("page button clicked")}>Something on the page</button> <Dialog open={open} onClose={() => setOpen(false)} title="Edit card"> <form method="dialog" onSubmit={(e) => setTitle(new FormData(e.currentTarget).get("title"))}> <p> <label> Title <input name="title" defaultValue={title} /> </label> </p> <div className="toolbar"> <button type="submit">Save</button> <button type="button" onClick={() => setOpen(false)}>Cancel</button> </div> </form> </Dialog> </main> ); } import { useEffect, useRef } from "react"; // The browser's own modal dialog: it moves focus inside, blocks the page // behind it, closes on Escape, and returns focus to whatever opened it. export default function Dialog({ open, onClose, title, children }) { const ref = useRef(null); // Keep the real <dialog> in step with the open prop. useEffect(() => { const dialog = ref.current; if (open && !dialog.open) dialog.showModal(); if (!open && dialog.open) dialog.close(); }, [open]); return ( <dialog ref={ref} onClose={onClose} aria-labelledby="dialog-title"> <h2 id="dialog-title">{title}</h2> {children} </dialog> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The backdrop is part of the <dialog> element itself, so a click there has event.target === dialog. A click on anything inside has a child as its target.

Hint 2: a first step

A click in the dialog's own padding is also on the <dialog>. Compare the click's position with dialog.getBoundingClientRect() to be sure it's outside.

Show one solution

In Dialog.jsx:

JSX
function handleClick(event) {
  const box = ref.current.getBoundingClientRect();
  const outside =
    event.clientX < box.left || event.clientX > box.right ||
    event.clientY < box.top || event.clientY > box.bottom;
  if (event.target === ref.current && outside) onClose();
}
JSX
<dialog ref={ref} onClose={onClose} onClick={handleClick} aria-labelledby="dialog-title">

Was this article helpful?

Your response is saved on this device.