React Portals allow you to render a child component into a DOM node that exists outside the parent component’s DOM hierarchy, while still keeping it part of the same React component tree.
In simple words:
Portals let React render UI somewhere else in the DOM without breaking React’s logic.
🧱 Basic Syntax
ReactDOM.createPortal(child, container)
🧪 Simple Example
HTML
<body>
<div id="root"></div>
<div id="modal-root"></div>
</body>
React Component
import ReactDOM from "react-dom";
function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.getElementById("modal-root")
);
}
Usage:
<Modal>
<h2>Confirm Action</h2>
</Modal>
✔ Modal renders inside modal-root
✔ Still behaves like a normal React component
🧠 Why Do We Need Portals?
Some UI elements break layout or styling when rendered inside parent components due to:
overflow: hiddenz-indexstacking- positioning constraints
Portals solve these issues cleanly.
✅ When Should You Use React Portals?
✔ 1. Modals & Dialogs
<LoginModal />
Avoids parent layout restrictions.
✔ 2. Tooltips & Popovers
Ensures correct positioning and layering.
✔ 3. Dropdowns
Prevents clipping inside scroll containers.
✔ 4. Toast Notifications
Render globally without nesting inside components.
✔ 5. Floating UI Elements
Context menus, alerts, overlays.
🔥 Important Behavior (Interview Tip)
Even though the DOM location is different:
- Event bubbling still works
- Events propagate through the React tree, not the DOM tree
<button onClick={handleClick}>
<PortalComponent />
</button>
✔ handleClick still fires
🆚 Without Portal vs With Portal
❌ Without Portal
- z-index issues
- clipped UI
- layout bugs
✅ With Portal
- clean layering
- predictable UI
- better accessibility
🎯 Short Interview Answer
React Portals allow rendering components outside their parent DOM hierarchy while keeping them in the same React tree.
They are commonly used for modals, tooltips, dropdowns, and overlays to avoid layout and z-index issues.
⭐ One-Line Summary
Portals solve UI layering problems without breaking React’s component structure.