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)