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)