Sub topic 1
The Problem: Clipped and Buried UI
Prerequisites
Assume you know function components, JSX, props, children, useState, useEffect, basic DOM nodes, event bubbling, and CSS positioning with z-index.
The problem: clipped and buried UI
Some UI belongs logically to a component but must appear elsewhere in the page. Modals, tooltips, dropdowns, and popovers are common examples.
Consider a modal inside a card:
<div class="card">
<Modal />
</div>The card might have overflow: hidden, which clips content outside its bounds. It might also create a stacking context with transform, opacity, or z-index. A large z-index on the modal cannot always escape that stacking context. Another ancestor may also cover the modal.
A portal solves this by rendering the modal into a higher-level DOM node, often a direct child of document.body.
Two trees: React components and DOM nodes
React maintains a component tree for rendering, state, props, context, and event handling. The browser maintains a DOM tree for layout, clipping, stacking, and native events.
These trees usually have the same shape, but a portal separates them:
The modal remains a child of Parent from React’s perspective. The browser sees its elements under document.body. This distinction lets CSS positioning avoid an interfering ancestor while React state and context remain available.
Rendering with `createPortal`
React DOM provides createPortal(children, domNode). It returns a React node that mounts children inside domNode.
import { createPortal } from 'react-dom';
function Modal({ children }) {
const portalRoot = document.getElementById('portal-root');
if (!portalRoot) return null;
return createPortal(
<div className="backdrop">
<div className="dialog" role="dialog" aria-modal="true">
{children}
</div>
</div>,
portalRoot
);
}The portal container should exist in the HTML:
<div id="root"></div>
<div id="portal-root"></div>Use a stable container rather than creating a new DOM node on every render. Later chapters add focus management, keyboard handling, server-rendering safeguards, and tests.
Exercise
Why might a modal with a very large z-index still appear behind another element?
Show answer
Its ancestor may create a stacking context, or an ancestor may clip it with overflow. The modal remains constrained by that DOM hierarchy until it renders through a portal.