Portals
This is not a full React tutorial. It focuses on one important pattern: rendering content into a different DOM location.
1) Portals
A portal lets React render a component into a different DOM node than the one it normally lives in.
Normally, JSX elements are rendered inside the nearest parent in the DOM tree. With a portal, you can mount the content somewhere else, such as a dedicated modal-root element that lives outside your app tree.
import { createPortal } from 'react-dom';
function Modal({ children }: { children: React.ReactNode }) {
const modalRoot = document.getElementById('modal-root');
if (!modalRoot) {
return null;
}
return createPortal(
<div
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0, 0, 0, 0.5)',
display: 'grid',
placeItems: 'center',
}}
>
{children}
</div>,
modalRoot
);
}
export default function App() {
return (
<>
<h1>Page content</h1>
<Modal>
<p>Dialog rendered into a portal</p>
</Modal>
</>
);
}
The modal-root element usually exists in the page HTML, for example:
<div id="modal-root"></div>
Portals are commonly used for:
- modals
- tooltips
- dropdowns
- popovers
- overlays that must escape a parent container
2) Why portals are useful
Without a portal, a modal or popup may be clipped by a parent element with overflow: hidden, z-index constraints, or other layout rules.
A portal lets the UI be rendered in a different DOM location while still being controlled by React. The component still behaves as part of the same React tree, but it is mounted into a different DOM container.
One useful detail: React events still bubble through the React tree even when the DOM node is elsewhere, so the portal can still work naturally with the surrounding component logic.
3) Summary
- portals render content into another DOM node instead of the normal component tree
- they are useful for overlays and components that must escape parent layout constraints
- React keeps the portal connected to the app tree, so events still work normally
This pattern is especially useful when building dialogs, overlays, and popups that need to escape their surrounding layout.
Top comments (0)