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.