Sub topic 3
Rendering with createPortal
This chapter covers the createPortal API: its signature, what it changes and what it leaves alone, and the mistakes that cause trouble in practice. It assumes you know function components, JSX, props and children, useState and useEffect, and basic DOM concepts such as nodes and document.body. You should also be comfortable with CSS positioning and z-index.
What createPortal does
A portal lets a component render its children into a DOM node that is not inside the component's own parent DOM element. The component stays in the same place in the React tree. Only the DOM output moves.
You create a portal with createPortal, which is exported from react-dom, not from react:
import { createPortal } from 'react-dom';
createPortal(children, domNode, key?)| Argument | Meaning |
|---|---|
| `children` | Anything React can render: JSX, strings, numbers, fragments, arrays. |
| `domNode` | A real DOM element that already exists when React commits the portal. |
| `key` | Optional string or number. It acts as a React key for the portal. You rarely need it. |
The return value is a React node. You return it from a component, or place it inside JSX, like any other element.
import { createPortal } from 'react-dom';
function Notice({ message }) {
return (
<section>
<p>This paragraph renders inside the section.</p>
{createPortal(
<p className="notice">{message}</p>,
document.body
)}
</section>
);
}When Notice renders, the first paragraph appears inside <section>. The second paragraph is appended to document.body. In the React tree, both paragraphs are children of Notice.
Why this solves clipping and stacking problems
A parent element can hide or bury a child in three ways:
overflow: hidden,overflow: autooroverflow: scrollon an ancestor clips descendants, even positioned ones, when that ancestor is the containing block or sits between the child and its containing block.- A new stacking context on an ancestor traps the child's
z-index. A stacking context is created by, for example,positionwith az-indexvalue,opacitybelow 1,transform,filter, orisolation: isolate. A child withz-index: 9999still cannot appear above a sibling of its stacking-context ancestor that has a higherz-index. - A
transformon an ancestor changes the containing block forposition: fixeddescendants. The "fixed" element then positions relative to that ancestor instead of the viewport.
Moving the DOM output to document.body, or to a dedicated container near the top of the page, removes the child from all of those ancestors. The child now competes in the root stacking context and is only clipped by the viewport.
A first realistic example: a modal
The following component renders a backdrop and a dialog as a child of document.body, so no parent overflow or z-index can clip or bury it.
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
>
{children}
</div>
</div>,
document.body
);
}Two details matter here.
- The backdrop has the
onCloseclick handler. Clicking the dark area closes the modal. - The dialog calls
e.stopPropagation(). Without it, a click inside the dialog would bubble up to the backdrop and close the modal. This is ordinary React event propagation, and it applies to portals as well as anything else.
You use Modal like any other component:
import { useState } from 'react';
function Card() {
const [open, setOpen] = useState(false);
return (
<div style={{ overflow: 'hidden', transform: 'translateZ(0)' }}>
<button onClick={() => setOpen(true)}>Open</button>
{open && <Modal onClose={() => setOpen(false)}>Hello</Modal>}
</div>
);
}The wrapper div has both overflow: hidden and a transform. Without a portal, a position: fixed modal inside it would be clipped and positioned relative to the wrapper. With the portal, the modal ignores the wrapper's styles.
The modal's state is owned by Card. When open becomes false, Modal is unmounted and React removes its DOM nodes from document.body.
What stays the same
A portal changes where DOM nodes go. It does not change how React manages the component. These things are unchanged:
- State and effects. Components inside a portal keep their state while mounted and run their effects as usual.
- Props. Data still flows down from the parent to the portal content as props.
- Context. A portal child reads context from its React ancestors, not from its DOM ancestors. Later chapters treat this in detail.
- Event bubbling. Events from portal content bubble to React ancestors, even though the DOM nodes are elsewhere.
The last point is the one that surprises people, so here is a short demonstration. The button lives in document.body, but the click still reaches Parent.
import { createPortal } from 'react-dom';
function Parent() {
return (
<div onClick={() => console.log('Parent received the click')}>
<PortalButton />
</div>
);
}
function PortalButton() {
return createPortal(<button>Click me</button>, document.body);
}React attaches its event listeners at the root container and simulates bubbling along the React tree. A synthetic event therefore follows the component hierarchy, not the DOM hierarchy. Native listeners that you attach yourself with addEventListener follow the DOM and will not see this behavior.
What changes
Several things do change when you use a portal:
- CSS inheritance. Inherited properties such as
color,font-familyandline-heightcome from the DOM parent. A portal indocument.bodyno longer inherits text color from a styled card. Style the portal content directly or give the container the base styles. - CSS selectors. A rule like
.card .tooltipno longer matches, because the tooltip is not a DOM descendant of.card. - DOM queries.
parent.contains(node)andelement.closest(...)use the DOM and give different answers than the React tree would. - Focus order. Keyboard Tab order follows the DOM. Content appended at the end of
bodyis last in Tab order unless you manage focus. - Layout. The portal content is no longer laid out as part of its parent. Position it explicitly.
The domNode argument
The second argument must be a real DOM element. If it is null or undefined, React throws an error such as "Target container is not a DOM element." That error is the most common failure with portals.
There are three typical choices:
document.body. Simple and always present in the browser. Many portals appended to it can make the body cluttered, and some third-party scripts that observebodywill see your nodes.- A dedicated element in your HTML, such as
<div id="portal-root"></div>next to your app root. This is predictable and easy to style. - An element you create yourself, appended in an effect and removed on cleanup.
If you look up a container by id, do it after the DOM exists. During server rendering there is no document, so a top-level document.getElementById(...) call fails. The following component finds the container in an effect. It renders nothing on the server and during hydration, then creates the portal on the client.
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function ClientPortal({ children, containerId = 'portal-root' }) {
const [container, setContainer] = useState(null);
useEffect(() => {
setContainer(document.getElementById(containerId));
}, [containerId]);
return container ? createPortal(children, container) : null;
}The first render returns null. After the effect runs, setContainer triggers a second render that creates the portal. This means the portal content appears one render later than ordinary content. For modals that open on user action this delay is invisible. For content that must be in the first paint, it is not suitable.
Later chapters cover container choice and server rendering in more depth.
Rendering into a container React does not own
React does not clear or manage the contents of the domNode you pass. It only adds and removes the nodes that belong to the portal. This has two consequences.
- You can share one container among many portals. Each portal manages only its own nodes.
- Do not render a portal into an element that React already renders as part of the same tree and updates, such as a node inside your own JSX. React may reconcile the parent and remove or reorder the portal's nodes. Use containers that live outside React's rendering, such as
bodyor an element inindex.html.
Do not pass the root container itself, such as the element given to createRoot, as the target of a portal. Use a separate sibling element.
Keys and multiple portals
A component can render several portals, and each one is an ordinary node in the tree. When portals appear in a list, give them keys the way you would for any list element. The third argument of createPortal is a key for the portal itself, which is useful when a component returns portals as siblings without a wrapper:
import { createPortal } from 'react-dom';
function Toasts({ toasts }) {
return toasts.map((toast) =>
createPortal(
<div className="toast">{toast.text}</div>,
document.body,
toast.id
)
);
}Here each toast has a stable id. Removing one toast unmounts only its portal.
Cleanup and lifecycle
Unmounting the component that created the portal removes the portal's DOM nodes. You do not remove them yourself. If you add your own side effects, such as a document listener, you must clean those up. The following hook closes a modal when Escape is pressed and removes its listener on cleanup.
import { useEffect } from 'react';
function useEscapeKey(onEscape) {
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') onEscape();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [onEscape]);
}The effect depends on onEscape. If the parent passes a new function on every render, the listener is removed and re-added each time. That is correct but wasteful. Wrap the callback in useCallback in the parent if it matters.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Target container is not a DOM element" | The container lookup returned `null`, for example because the element is missing or the code ran before the DOM was ready. | Check the element exists in your HTML. Look it up in an effect. |
| `document is not defined` on the server | `document` was read while rendering. | Read it inside `useEffect`. |
| Portal content has the wrong font or color | CSS inheritance follows the DOM parent. | Style the content directly or style the container. |
| Clicking inside the modal closes it | The click bubbled to the backdrop handler. | Call `e.stopPropagation()` on the dialog, or compare `e.target` with `e.currentTarget` on the backdrop. |
| An outer handler fires unexpectedly | React events bubble through the React tree. | Stop propagation at the portal boundary if the parent should not react. |
| Content still appears behind other UI | The container is itself inside a stacking context. | Put the container directly under `body`. |
Summary of the mental model
createPortal(children, domNode)returns a node that renderschildrenintodomNode.- The component's position in the React tree does not change. State, props, context and synthetic event bubbling follow the React tree.
- DOM-level behavior follows the DOM tree: CSS inheritance, selectors, Tab order,
contains, and native listeners. - The target must exist when the portal commits, so look it up in an effect if the code can run on the server.
- React removes the portal's nodes on unmount. You clean up only your own listeners and other side effects.
Exercise
A Tooltip component uses createPortal(<div className="tip">{text}</div>, document.body) inside a div with className="card". The CSS has .card { color: red; } and .card .tip { font-weight: bold; }. The tooltip text is black and not bold. Explain why, and name one way to fix it.
Show answer
The tooltip's DOM parent is document.body, not .card. Color is an inherited property that comes from the DOM parent, so the text does not inherit red from .card. The selector .card .tip requires .tip to be a DOM descendant of .card, so it never matches. Fix it by styling the tooltip directly, for example .tip { color: red; font-weight: bold; }, or by putting the styles on the portal container.
Exercise
In the Parent and PortalButton example, a click on the button in document.body logs "Parent received the click". Would a native listener added with parentDiv.addEventListener('click', ...) on the DOM element rendered by Parent fire for the same click? Why or why not?
Show answer
No. A native listener follows DOM bubbling, and the button is not a DOM descendant of the parent div. The click bubbles from the button to body and document, never through the parent div. The React onClick handler fires because React synthetic events bubble along the React tree, where PortalButton is a child of Parent.