The " Visual Cage " Problem
In the web, everything is hierarchical. Imagine you're making a beautiful product card. Inside the card is a " Buy " button that opens a modal window.
But here's the trouble: the card itself has the style overflow: hidden (to round the edges).
Result: Your modal window is simply cut off by the card's borders. It's locked inside its parent.
1. Solution: Portals (Teleportation)
Portal allows a component to remain part of the React tree (pass props, have access to context), but physically render in a completely different place in the DOM tree (e.g., at the very end of the <body> tag).
2. Analogy: Secret Passage
Imagine you're in a tiny closet (Parent). But you have a portal in the wall. You stick your hand through it, and it appears in a huge throne room (document.body).
- You're still standing in the closet (logically you're in the parent).
- But your hand is free and visible to everyone (visually you're outside).
3. How to Write This?
We use the createPortal function from the react-dom package:
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal-overlay">
{children}
</div>,
document.body // Where we "spit out" our markup
);
}
4. Portal Magic: Event Bubbling
This is the coolest part. Although physically your modal block is at the end of the page, React pretends it's still inside the parent. If you press a button in the modal, the click event will " bubble up " to the parent that created it. This allows handling clicks in one place, even if interface parts are visually scattered across the screen.
5. Why Do We Need This?
- Modal windows and dialogs: So they're always on top and not cut off.
- Tooltips and hints: So they don't break container layouts.
- Dropdown menus: That should hover over the list, not push it apart.
Portals are a way to cheat HTML physics while maintaining order in React logic.