React Portals

React Portals

Portals let you render part of a React tree into a different DOM node from the one owned by the parent component. That sounds unusual, but it is exactly what you want for modals, tooltips, popovers, and dropdown layers that must escape overflow or z-index problems.

Creating a Portal

You use createPortal(child, container) from react-dom to render content into another element in the document.

import { createPortal } from 'react-dom';

function Modal({ children }) { return createPortal(children, document.getElementById('modal-root')); }

Why Portals Help

Practical Example

Your page can render the main app inside #root, while a modal renders inside #modal-root placed at the end of body. The portal still behaves like part of the same React tree, so state and props work normally.

Common Pitfalls

When To Use It

Use portals for interface layers that must sit above the normal page flow. For ordinary content, keep the component in the usual tree so the code stays easier to follow.