What are React Portals?
React Portals provide a seamless mechanism to render child components outside their parent DOM hierarchy while still preserving the React context and parent-child relationship. In simpler terms, with portals, you can position a component’s rendering into a different location in the DOM, distinct from its position in the React tree.
A common use case for portals is when dealing with modals, pop-ups, and overlays. For instance, you might want a modal dialog to be rendered as a direct child of the `body` tag to avoid CSS stacking context or overflow issues. But within the React component tree, this modal might reside deep within other components. Portals bridge this gap by allowing the modal to be rendered directly under `body` in the DOM, yet still be part of the React component hierarchy where it logically belongs.
To create a portal, React provides the `ReactDOM.createPortal()` method. This method takes two arguments: the first is the JSX or React element you want to render, and the second is the DOM node where you wish to render the given element.
While portals can render anywhere in the DOM, they behave like a normal React component in every other way. Events on a portal still propagate to its ancestors in the React tree, despite the DOM node being outside that hierarchy. This ensures a consistent behavior in your application, regardless of the positioning of elements in the DOM.
React Portals introduce a powerful way to handle certain UI challenges, especially when the desired DOM position differs from the logical position in the React tree. By breaking the container constraints without forsaking the benefits of the React model, portals exemplify the flexibility and adaptability of React’s design philosophy.