React Portals: Breaking Out of DOM Hierarchy

🚀 Day 22 – React Portals (Break Out of the DOM Tree) As your UI grows, you may face layout issues: ⚠️ Modals hidden behind elements ⚠️ Tooltips getting clipped ⚠️ z-index not working as expected The problem is not CSS… 👉 It’s DOM hierarchy 🛒 Simple Analogy Imagine a building 🏢 🔴 Without Portal You’re stuck inside nested rooms 👉 Your message stays hidden inside 👉 No one outside can see it 😓 🟢 With Portal You use an emergency exit 🚪 👉 Jump outside the building 👉 Now everyone can see your message 👉 That’s React Portal: Render outside parent hierarchy 🧠 Why Portals Matter Without Portals: • Content gets clipped • z-index issues • Poor UI layering With Portals: • Clean overlays • Proper layering • Better UX 💻 1. Without Portal (Problem) function App() { return ( <div style={{ overflow: "hidden" }}> <Modal /> {/* ❌ Might get clipped */} </div> ); } 💻 2. With Portal (Solution) import ReactDOM from "react-dom"; function Modal({ children }) { return ReactDOM.createPortal( <div className="modal">{children}</div>, document.getElementById("modal-root") ); } ✅ Renders outside parent ✅ No clipping issues 💻 3. HTML Setup <div id="root"></div> <div id="modal-root"></div> ⚡ How It Works 👉 Component stays in React tree 👉 But renders in different DOM node 📌 Key Concepts ✔ createPortal(child, container) ✔ Breaks out of parent DOM hierarchy ✔ Keeps React logic intact 🧠 Common Use Cases • Modals • Tooltips • Dropdowns • Notifications ⚠️ Important Note 👉 Events still bubble up through React tree 👉 Even if DOM position is different 💬 Developer Question Where do you use portals the most? 1️⃣ Modals 2️⃣ Tooltips 3️⃣ Dropdowns 4️⃣ Notifications #React #FrontendDevelopment #JavaScript #WebDevelopment #ReactJS #UIUX #CodingJourney 🚀

  • graphical user interface, website

To view or add a comment, sign in

Explore content categories