Portals
Portals let you render a child component into a DOM node that exists outside the parent component's DOM hierarchy — useful for modals, tooltips, and dropdowns that need to escape parent overflow/z-index constraints.
Even though the DOM node is elsewhere, the portal content still behaves like a normal React child for events and context.
Creating a portal
Use `ReactDOM.createPortal(child, domNode)` where `domNode` is typically a separate element like `#modal-root` in your HTML.
Why use portals
Modals often need to render above all other content, unaffected by a parent's CSS `overflow: hidden` or `z-index` stacking context.
import { createPortal } from "react-dom";
function Modal({ children }) {
return createPortal(
<div className="modal">{children}</div>,
document.getElementById("modal-root")
);
}(renders the modal into #modal-root, outside the app's div)The modal content appears in a different DOM node than the parent component.
Key points
- Portals render children into a DOM node outside the parent hierarchy.
- Created with ReactDOM.createPortal(child, domNode).
- Commonly used for modals, tooltips, and popovers.
- Events still bubble through React's tree, not the actual DOM tree.
