Command Palette

Search for a command to run...

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

A custom modal: remember, trap, restore

The script presses keys by dispatching keydown events, the same way the exercises test you. Each of the four numbered steps is one line; forgetting any of them is a real accessibility bug. The portal (Topic 8.5) keeps the modal outside #app, so making #app inert doesn't hide the modal itself.

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 custom modal: remember, trap, restore

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

opened, focus: INPUT
Tab from Cancel wraps to: INPUT
Shift+Tab from the first field wraps to: Cancel
after Escape, focus: rename