A React Portal allows you to render a React component outside its parent DOM hierarchy, while still keeping it part of the same React component tree.
🔹 Why Do We Need React Portals?
Normally, React renders components inside their parent DOM node.
This causes problems for:
- Modals
- Tooltips
- Dropdowns
- Popups
because of:
overflow: hiddenz-indexissues- stacking context problems
👉 Portals solve this by rendering outside the parent DOM tree.
🧠 How React Portal Works
- Visually renders elsewhere in the DOM (usually under
<body>) - Logically remains inside the React tree
- Props, state, and context still work normally
✅ How to Create a React Portal
1️⃣ Add a DOM Node in index.html
<body>
<div id="root"></div>
<div id="portal-root"></div>
</body>
2️⃣ Create Portal Component
import ReactDOM from "react-dom";
function Modal({ children }) {
return ReactDOM.createPortal(
children,
document.getElementById("portal-root")
);
}
export default Modal;
3️⃣ Use the Portal
function App() {
return (
<div>
<h1>Main App</h1>
<Modal>
<div className="modal">
<h2>Modal Content</h2>
</div>
</Modal>
</div>
);
}
🔥 Important Points
✔ Events still bubble to parent components
✔ Context API works
✔ Solves z-index & overflow issues
✔ Ideal for overlays
❌ What Portals Do NOT Do
- ❌ Do not change React tree structure
- ❌ Do not break event handling
- ❌ Do not isolate state
🎯 Short Interview Answer
React Portal allows rendering children into a DOM node outside the parent hierarchy using
ReactDOM.createPortal.
It is commonly used for modals, tooltips, and overlays to avoid z-index and overflow issues while preserving React’s event system.
⭐ One-line summary
React Portal renders UI outside the DOM tree but inside the React tree.