Command Palette

Search for a command to run...

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

Toasts and a tooltip in their own layer

Toasts render into a second div that is a live region, so screen readers announce them. Hover Save: the tooltip is measured in a layout effect and portaled to <body>, so the clipping box can't cut it off.

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?

Toasts and a tooltip in their own layer

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

toasts: [ 'Saved draft 1', 'Saved draft 2' ]