38. Portals
Rendering Outside the Hierarchy
In standard React, a component renders its children directly inside its own DOM node. However, this creates massive problems for UI elements that need to float above everything else, like Modals, Tooltips, and Dropdowns. If a parent container has overflow: hidden or a restrictive z-index, your modal will be cut off or trapped behind other elements.
Introducing React Portals
Portals provide a first-class way to render children into a completely different DOM node that exists outside the DOM hierarchy of the parent component, while still behaving logically like a normal React child.
Why Portals are Magic (Event Bubbling)
Even though a portal physically injects the HTML into a different part of the actual webpage (the physical DOM tree), it remains exactly where it was in the React Tree. This means if you click a button inside the teleported Modal, the onClick event will still bubble up to the React parent component that originally rendered the Modal. Context works perfectly through Portals as well!
Knowledge Check
Ready to test your understanding of 38. Portals?