What Are React Portals?
React Portals allow you to render components outside the main DOM hierarchy of the parent component.
This is useful for modals, tooltips, and overlays.
Basic Syntax
ReactDOM.createPortal(child, container)
child→ React element to rendercontainer→ DOM node to render into
Example: Modal Using Portal
import React from "react";
import ReactDOM from "react-dom";
function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.getElementById("modal-root")
);
}
function App() {
return (
<div>
<h1>My App</h1>
<Modal>
<p>This is a portal modal!</p>
</Modal>
</div>
);
}
Key Points
- Renders outside parent DOM tree
- Useful for modals, tooltips, popups
- Still part of React component hierarchy
- Can access props, state, and context normally
Conclusion
React Portals help render UI elements outside parent hierarchy, improving flexibility for overlays and modals while keeping React logic intact.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP