React Portals
⚛️ React Portals
React Portals provide a way to render components outside of the main root DOM hierarchy — while still keeping them logically inside React’s component tree.
Portals are commonly used for:
Modals / Dialogs
Tooltips
Dropdown menus
Toast notifications
Pop-ups that must appear above everything else
🔹 Why Use a Portal?
Normally, React renders everything inside the element with:
But sometimes, you need to render UI outside this container (like modals overlaying the entire page).
React Portals allow that.
🔹 Creating a Portal
📁 1. Update HTML Structure
In your public/index.html, add another DOM node:
📁 2. Create a Portal Component
📁 3. Use It
Even though it’s defined inside App, the content appears inside #portal-root in the browser.
🧪 Example: Modal Using Portal
🔍 How It Works
| Without Portal | With Portal |
|---|---|
Component is rendered inside #root only | Component is rendered in any DOM location |
| Hard to style overlays | Easy to manage pop-ups, modals, overlays |
| Z-index issues | Better UI layer control |
🧠 Key Notes
✔ Portals maintain React state and event propagation
✔ Clicking inside the Portal still triggers parent components’ event listeners
✔ Useful for UI layering and accessibility
🎯 Summary
React Portals let you:
Render children in a different part of the DOM
Without breaking React’s component hierarchy
Ideal for modals, tooltips, dropdowns, pop-ups
