Command Palette

Search for a command to run...

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

Events bubble through the React tree, not the DOM tree

The normal button's click reaches both listeners. The portal button lives in <body>, so the native listener on #root never hears it, but the React onClick on the card still does: React bubbles events through its own tree.

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?

Events bubble through the React tree, not the DOM tree

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

portal button's DOM parent: <body>
native listener on #root: click on inside
React parent onClick: click on inside
React parent onClick: click on portaled