React Portals
A portal lets you render a child component into a different DOM node that is outside the parent component's hierarchy.
Syntax
tsx
import { createPortal } from 'react-dom';
function Modal({ children }: { children: React.ReactNode }) {
return createPortal(
<div className="modal">{children}</div>,
document.getElementById('modal-root')!
);
}When to use
- Modals - to avoid
z-indexandoverflow: hiddenissues from parents. - Tooltips and dropdowns - positioning relative to the viewport.
- Notifications (toasts) - fixed place in the DOM.
Important
Even though a Portal renders its element elsewhere in the DOM:
- Events bubble through the React tree, not the DOM tree.
- Context works normally - a Portal is a child in the React hierarchy.
html
<!-- HTML structure -->
<div id="app">...</div>
<div id="modal-root">
<!-- Portal renders here -->
</div>updated
did you know it?