Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 24.8 — Modals, Toasts, Tooltips and Menus
React · Example 1 of 3

A modal built on the native dialog

showModal() moves focus to the autoFocus button and makes the page inert. The script simulates Escape (a cancel event, then the browser closes the dialog); onClose sets the state, and the browser puts focus back on the opener. Open it yourself and press Tab and Escape.

Overlays float above the page, so they must escape clipping and stacking (portals or the browser's top layer), manage focus (trap it in modals, return it on close), dismiss predictably (Escape, outside click), position themselves next to their trigger without leaving the screen, and, for toasts, queue up, time out and pause while the user reads.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Add a type ("success" or "error") to the toast system; errors use role="alert" and don't auto-dismiss.

02

Make the tooltip also shift sideways so it never goes past the right edge of the window.

Explain it without notes

01

Why do overlays need portals or the top layer?

02

What does <dialog>.showModal() give you, and how do you use it from React?

03

Design a toast system: API, queueing, timing and accessibility.

04

How do you position a tooltip so it stays on screen?

A modal built on the native dialog

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Open: modal true, focus on Cancel
After Escape: open false, focus back on opener