Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.5 — Portals
React · Example 1 of 3

A modal that escapes a clipping card

The modal's DOM sits in <body>, outside the clipping card, so it covers the page. Focus moves into the dialog on open, Escape closes it, and the effect's cleanup returns focus to the button.

createPortal(children, domNode) renders part of your component's output into a different DOM element, such as document.body, while it stays in the same place in the React tree: props, context and even events still flow as if it were rendered in place.

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 Toast component that portals a message into document.body and removes itself after 2 seconds.

02

Write a dropdown menu inside an overflow: hidden box whose list is portaled to document.body and positioned under the button.

Explain it without notes

01

What is a portal and when would you use one?

02

A button inside a portal is clicked. Which onClick handlers run: those of its DOM ancestors or its React ancestors? Why?

03

What must you do to make a portal-based modal accessible?

04

What is the difference between a portal and a second createRoot?

A modal that escapes a clipping card

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

dialog lives in: <body>
focus is on: <div.modal>
after Escape, dialog open: false
focus is back on: <button#open>