Sub topic 2
Two trees: React components and DOM nodes
This chapter assumes you can write function components in JSX, pass props and children, and use useState, useEffect and useRef. It also assumes you know what DOM nodes and document.body are, and how CSS positioning and z-index behave. By the end you should be able to say which of React's two trees any given behavior follows. Portals depend on that distinction.
Two trees, two jobs
A running React app maintains two separate structures.
- The React tree (also called the component tree) is the hierarchy of component instances. A parent in this tree is the component whose JSX rendered the child.
- The DOM tree is the hierarchy of real browser nodes:
div,button, text nodes and so on. A parent in this tree is the node the child was inserted into.
React reads the first tree and writes the second. Components such as App, Modal or ThemeProvider exist only in the React tree. Browser APIs like querySelector and getBoundingClientRect see only the DOM tree.
Most of the time you never need to separate the two, because they line up closely. Portals are the feature where they stop lining up, so this chapter sets up the vocabulary the next ones rely on.
The React tree
Each time a component renders, React records who rendered whom. If Page returns <Sidebar /> and <Content />, those are its children in the React tree. The tree carries the things React manages for you:
- Props flow down from parent to child.
- State belongs to a component instance, and it is preserved or reset depending on whether that instance stays in the same position in the tree.
- Context is looked up by walking up the React tree to the nearest matching provider.
- Error boundaries catch errors thrown by their descendants in the React tree.
- React's synthetic events bubble upward through React ancestors.
Components that render no DOM at all still appear in this tree. A context provider, a fragment wrapper or a custom hook's host component adds a level to the React tree but nothing visible to the DOM.
The DOM tree
The DOM tree is what the browser works with. It decides:
- How CSS selectors match, including descendant selectors such as
.card .title. - Which properties are inherited, such as
color,font-familyandline-height. - Where an element is laid out, and which ancestor's
overflowclips it. - Which stacking context an element belongs to, which controls whether
z-indexcan lift it above other content. - What
element.parentElement,element.closest()andelement.contains()return. - The default Tab order, which follows DOM order.
- Which nodes a screen reader sees as nested inside which others.
React updates the DOM tree through browser APIs, creating, changing and removing nodes. The DOM never holds components. A component has no DOM node of its own unless it renders one.
Usually they match
In an ordinary app, a component's DOM output lands inside the DOM output of its parent. This component:
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
function App() {
return (
<main>
<Card title="Profile">
<p>Hello</p>
</Card>
</main>
);
}produces two trees that are close to mirror images, except that the React tree has extra component levels:
<main>
<section class="card">
<h2>Profile</h2>
<p>Hello</p>
</section>
</main>The React tree here is App > Card > (section, h2, p). The DOM tree is main > section > (h2, p). Card and App are in one tree only, but the host elements (main, section, h2, p) have the same relative nesting in both. This is why you can usually reason about only one of them.
Where they diverge
A portal lets a component say: "render my children into a different DOM node, but keep them in my place in the React tree." The API is createPortal(children, domNode). The next chapter covers it in detail. Here it serves as the example of divergence.
import { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
function Probe({ label }) {
const ref = useRef(null);
useEffect(() => {
console.log(label, 'DOM parent:', ref.current.parentElement.tagName);
}, [label]);
return <span ref={ref}>{label}</span>;
}
export default function App() {
return (
<section id="card" style={{ overflow: 'hidden' }}>
<Probe label="inline" />
{createPortal(<Probe label="portal" />, document.body)}
</section>
);
}Both Probe instances are children of App in the React tree. In the DOM they are in different places, and the console shows:
inline DOM parent: SECTION
portal DOM parent: BODY(In development with StrictMode, effects run twice, so you will see each line twice.)
The following diagram shows both trees for this example. The dashed arrow marks the portal link.
In the React tree, both probes sit under App. In the DOM, the portal's span is a sibling of the section rather than a descendant. The overflow: hidden on the section cannot clip it, because clipping follows DOM ancestors.
Which tree decides what
When something behaves unexpectedly, ask which tree owns that behavior.
| Behavior | Follows |
|---|---|
| Props and `children` | React tree |
| State and its lifetime | React tree |
| Context value lookup | React tree |
| Error boundary catching | React tree |
| React `onClick` and other synthetic event bubbling | React tree |
| CSS selectors and inherited properties | DOM tree |
| `overflow` clipping | DOM tree |
| `z-index` and stacking contexts | DOM tree |
| `parentElement`, `closest`, `contains` | DOM tree |
| Native listeners from `addEventListener` | DOM tree |
| Default Tab order | DOM tree |
| Layout (flex, grid, positioning containing block) | DOM tree |
Keep this table in mind. Most portal bugs come from assuming that a behavior in one row also holds for the other tree.
Three consequences you will meet
Inherited styles do not follow the React parent
Suppose a card sets color: crimson in CSS. Text in an inline child inherits that color. Text in a portal child does not, because its DOM parent is body.
.card {
color: crimson;
font-size: 18px;
}import { createPortal } from 'react-dom';
function Card() {
return (
<div className="card">
<p>Inline text is crimson.</p>
{createPortal(<p>Portal text is not.</p>, document.body)}
</div>
);
}The fix is to style the portal content directly, for example with its own class, or to use CSS custom properties defined on a shared ancestor such as :root. Selectors like .card .tooltip will not match portal content either.
Context does follow the React parent
Context is the opposite case. Values are resolved through the React tree, so a portal child still sees providers above its React parent. This is why a theme provider can control a modal even though the modal's DOM node is far away.
import { createContext, useContext } from 'react';
import { createPortal } from 'react-dom';
const ThemeContext = createContext('light');
function PortalLabel() {
const theme = useContext(ThemeContext);
return createPortal(<p>Theme: {theme}</p>, document.body);
}
export default function App() {
return (
<ThemeContext.Provider value="dark">
<PortalLabel />
</ThemeContext.Provider>
);
}The paragraph is a child of body, yet it renders Theme: dark. The context chapter later in this tutorial covers this in depth.
Containment checks give different answers
React synthetic events bubble along the React tree, but contains() checks the DOM tree. Code that combines the two can contradict itself:
import { createPortal } from 'react-dom';
function Panel() {
function handleClick(event) {
const insideDom = event.currentTarget.contains(event.target);
console.log('React handler ran. Target inside in the DOM?', insideDom);
}
return (
<div onClick={handleClick}>
<button>Inline</button>
{createPortal(<button>Portal</button>, document.body)}
</div>
);
}Clicking "Inline" logs true. Clicking "Portal" still runs the handler, because the portal button is a React descendant of the div, but it logs false. A common "click outside to close" implementation that relies on contains() therefore treats clicks in portal content as outside clicks. If you need to handle this, check the target against both the main element and the portal element.
Components are not nodes
A related point: one component does not mean one DOM node. A component can render any of these:
- One host element, such as
<section>. - Several sibling elements through a fragment,
<>...</>. - Nothing, by returning
null. - Text only.
So parentElement of a component's output is the DOM parent of its first node, not "the component's parent". There is also no component-to-node API. If you need a node, put a ref on a host element. Do not use the deprecated findDOMNode.
Inspecting both trees
Browser tools show each tree separately.
- The Elements panel in browser developer tools shows the DOM tree. Portal content appears under its container, such as
body, not under the component that created it. - The Components tab in React DevTools shows the React tree. Portal content appears under its React parent, labeled as a portal.
When a bug involves clipping, stacking or CSS, look at the DOM tree. When it involves state, context or event handlers, look at the React tree. Looking at both side by side is the fastest way to see a divergence.
Summary of the mental model
- The React tree is who rendered whom. It governs props, state, context, error boundaries and synthetic event bubbling.
- The DOM tree is where nodes are inserted. It governs CSS, layout, clipping, stacking, native events and DOM queries.
- Usually the two nest the same way. A portal breaks that for one subtree: it keeps its React parent and gets a different DOM parent.
- When a behavior surprises you, decide which tree it follows, then check that tree.
Exercise
A Tooltip component renders its content with createPortal(..., document.body). It is used inside a <div class="sidebar"> whose CSS sets color: gray and overflow: hidden. The app is wrapped in a LocaleContext.Provider value="fr". For each of these, say whether the tooltip is affected as if it were still inside the sidebar: (1) the gray text color, (2) the overflow: hidden clipping, (3) the value of useContext(LocaleContext), (4) a React onClick handler on the sidebar div.
Show answer
(1) No. Color inheritance follows the DOM tree, and the tooltip's DOM parent is body, so it does not inherit gray. (2) No. Clipping follows DOM ancestors, so the sidebar cannot clip it. (3) Yes. Context follows the React tree, so the tooltip reads "fr". (4) Yes. Synthetic events bubble through the React tree, so a click in the tooltip reaches the sidebar's onClick, even though sidebar.contains(event.target) would be false.
Exercise
In the Probe example, how could you confirm in the browser which node is the portal's DOM parent, and which tool shows that the portal still belongs to App in the React tree?
Show answer
Inspect the portal's span in the browser's Elements panel and check that it sits under body, or log ref.current.parentElement. Open the Components tab in React DevTools to see the portal's Probe listed as a child of App.