Sub topic 2
Choosing a Portal Container
Assume you know function components, JSX, props, hooks, basic DOM nodes, CSS positioning, and z-index.
Choosing a Portal Container
A portal container is the DOM node that receives portal content. Use a dedicated node such as <div id="portal-root"></div> when your application has one. Use document.body for small applications or truly global UI.
A dedicated container makes ownership clearer and prevents unrelated code from sharing the same DOM node. The container must exist before createPortal runs.
import { createPortal } from 'react-dom';
function ClientPortal({ children }) {
const container = document.getElementById('portal-root');
return container ? createPortal(children, container) : null;
}If the container can be added or removed dynamically, find it in an effect and render nothing until it is available. This also helps with server-rendered applications, where document does not exist on the server.
Building a Modal Dialog
A modal commonly needs to escape an ancestor with overflow: hidden, a clipping boundary, or a stacking context. Render the backdrop and dialog together so they share positioning and layering.
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
const container = document.getElementById('portal-root');
if (!container) return null;
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
onClick={(event) => event.stopPropagation()}
>
{children}
</div>
</div>,
container
);
}The backdrop closes the modal when clicked. Stopping propagation prevents a click inside the dialog from reaching the backdrop. An accessible production modal should also manage focus, close on Escape, and return focus to the triggering control.
Events Bubble Through the React Tree
Portal events bubble according to the React tree, even when the DOM nodes are far apart. A button rendered into document.body can still trigger an onClick handler on its React parent.
This is useful for shared state and event handling, but it can surprise you when a parent handler should not receive a portal event. Stop propagation inside the portal when necessary.
Exercise
Why can a React parent receive a click from a button rendered through a portal?
Show answer
Events propagate through the React component tree, even though the button is mounted elsewhere in the DOM.