DEV Community

Aman Kureshi
Aman Kureshi

Posted on

πŸšͺ React Portals β€” Render Components Outside the Main DOM Hierarchy

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")
  );
}

Enter fullscreen mode Exit fullscreen mode

πŸ“¦ HTML setup:

<div id="root"></div>
<div id="modal-root"></div>

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Usage:

<Modal>
  <h2>This is a modal!</h2>
</Modal>

Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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)