React Portals allow you to render a component’s children into a different part of the DOM — outside of its parent component’s hierarchy — while still keeping React’s event system and state management intact.
In short: Portals let you place React elements somewhere else in the DOM without breaking the React tree.
🧩 Example
Let’s say your app’s structure looks like this:
<div id="root"></div>
<div id="modal-root"></div>
Normally, everything renders inside #root, but sometimes you want to render UI elements — like modals, tooltips, or dropdowns — at the top level of the DOM to avoid CSS overflow or stacking issues.
✅ Using a Portal:
// Modal.js
import ReactDOM from "react-dom";
export default function Modal({ children }) {
const modalRoot = document.getElementById("modal-root");
return ReactDOM.createPortal(children, modalRoot);
}
Then use it like:
// App.js
import React, { useState } from "react";
import Modal from "./Modal";
export default function App() {
const [open, setOpen] = useState(false);
return (
<div>
<h1>Main App</h1>
<button onClick={() => setOpen(true)}>Open Modal</button>
{open && (
<Modal>
<div className="modal">
<p>This modal is rendered outside #root!</p>
<button onClick={() => setOpen(false)}>Close</button>
</div>
</Modal>
)}
</div>
);
}
🧭 Here, even though the modal renders inside #modal-root, React still maintains the correct event bubbling and component hierarchy — setOpen(false) still updates App state!
⚙️ How It Works
ReactDOM.createPortal(child, container)
child→ React node(s) to render.container→ DOM element to render into (e.g.document.getElementById('modal-root')).
🎯 Common Use Cases
| Use Case | Why Portals Help |
|---|---|
| Modals / Dialogs | Avoids being hidden by parent’s CSS overflow: hidden |
| Tooltips / Popovers | Can render above other elements without layout issues |
| Dropdowns / Menus | Keeps them visually above other content |
| Global notifications / Toasts | Place them outside the main app hierarchy |
🧱 Summary
| Concept | Description |
|---|---|
| Definition | Way to render children into a different part of the DOM |
| API | ReactDOM.createPortal(child, container) |
| Maintains event bubbling? | ✅ Yes |
| Main use cases | Modals, popups, tooltips, dropdowns |
In short:
🌀 React Portals let you render components outside their parent DOM hierarchy — perfect for modals, tooltips, and overlays — while keeping them part of the same React tree.