Portals
Definition
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. They are created using `ReactDOM.createPortal(child, container)`.
Explain Like I'm New
Usually, React components are like nesting dolls. If a parent has `overflow: hidden` or a `z-index`, the child is trapped inside those CSS rules. A Portal is like a magical teleportation ring. You code the component exactly where it belongs in your React logic, but React physically teleports the HTML to a completely different part of the actual webpage (like the bottom of the `<body>` tag).
Real World Example
Modals, Tooltips, and Dropdown menus. If you put a modal inside a deep nested `<div>`, it might get cut off by the parent's boundaries. By teleporting the modal to a `<div id="modal-root">` attached directly to the `<body>`, it breaks free of all CSS restrictions and floats perfectly over the app.
Common Use Cases
- •Modals and Dialog boxes
- •Tooltips and Hovercards
- •Global Notifications / Toast messages
Interactive Example
Interview Questions
basic
- What is `ReactDOM.createPortal`?
- Why are Portals primarily used for Modals?
intermediate
- If you teleport a component using a Portal, does it lose access to the React Context of its parent?
- Does event bubbling work normally through a Portal?
advanced
- How do you test a component that uses a Portal?
- Can you render a Portal on the Server Side (SSR)?
trick
- If a child inside a portal throws an error, will an Error Boundary in the parent's React tree catch it?