Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Portal is a mechanism in React that allows rendering a component outside the main DOM tree, while still remaining part of the React hierarchy.
This is useful when you need to display modal windows, tooltips, dropdowns that shouldn't be nested within parent styles (e.g., overflow: hidden, z-index, transform).
React provides a special method:
ReactDOM.createPortal(children, container)
children — element to rendercontainer — DOM element where JSX will be placed outside current treeimport { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal">{children}</div>,
document.getElementById('modal-root') // outside app root
);
}
HTML
<body>
<div id="root"></div>
<div id="modal-root"></div> <!-- portal renders here -->
</body>
Now Modal component won't be wrapped in #root parent styles, but React will still manage its state and lifecycle.
z-index, overflow, positionConclusion:
Portal is a powerful React tool when you want to visually break out of parent DOM, while maintaining React control. Use them for modals, tooltips and any UI elements that should be "on top" of everything.