eact Portals let you render a component's content into a different part of the DOM than its parent component.
π― Why use React Portals?
β’ Perfect for modals, popups, tooltips, or floating UI elements
β’ Keeps styling and z-index issues manageable
β’ Still maintains full React event bubbling
π§ Example:
import ReactDOM from "react-dom";
function Modal({ children }) {
return ReactDOM.createPortal(
children,
document.getElementById("modal-root")
);
}
π¦ HTML setup:
<div id="root"></div>
<div id="modal-root"></div>
π‘ Usage:
<Modal>
<h2>This is a modal!</h2>
</Modal>
π Key points:
β’ Use ReactDOM.createPortal(content, targetNode)
β’ Useful for UI elements that should break out of parent container constraints
β’ Still part of the React tree logically, even if rendered elsewhere in the DOM
React Portals make complex UI patterns easier and more maintainable.
Top comments (0)