Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 18.2 — Managing Focus
React · Example 2 of 3

A native <dialog> moves, traps and restores focus

The browser did the hard parts: focus moved inside (the effect then picked Cancel over the first button, Delete), the page behind refused focus, and closing put focus back on the opener. Open it yourself and press Escape: onClose keeps React's open state in step.

Keyboard and screen reader users follow focus, so when React swaps content, changes the route or opens a modal, you must decide where focus goes: to the new page's heading, into the dialog, and back to the button that opened it.

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

Write a useFocusOnChange(ref, value) hook that focuses ref.current whenever value changes, but not on the first render.

02

Write the effect for a custom popover that remembers the opener when it opens and restores focus when it closes.

Explain it without notes

01

Why do single-page apps need explicit focus management on route changes, and how would you implement it?

02

List everything an accessible modal must do with focus, and say which parts <dialog> with showModal() gives you.

03

What happens to focus when React unmounts the focused element, and how do you handle it?

04

What is a skip link and why does its target need tabIndex={-1}?

A native <dialog> moves, traps and restores focus

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

open: true | focus: Cancel
tried to focus the page behind, focus: Cancel
open: false | focus: open