What are Portals in React and When to Use Them?
In React, Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component.
Normally, components are rendered within their parent DOM structure. However, with a Portal, you can render a component outside of this parent DOM tree while still maintaining the React context and event handling.
Syntax Example:
import ReactDOM from 'react-dom'; function MyPortalComponent() { return ReactDOM.createPortal( <div className="modal"> This is rendered through a Portal! </div>, document.getElementById('portal-root') // Target container outside the main app root ); }
In the example above, the <div>
will be inserted into the portal-root
element (which you must have in your HTML), not inside the normal React root node.
When to Use Portals?
You should consider using Portals when you need to render a component that visually or behaviorally should "break out" of the parent container. Common use cases include:
- Modals and Dialogs: A modal window should appear on top of everything else in the app.
- Tooltips and Popovers: They often need to be rendered outside their parent for proper positioning.
- Dropdowns: Complex dropdowns that overflow the parent container can use portals to render correctly.
Why are Portals useful?
- They help avoid CSS overflow and z-index issues.
- They maintain event bubbling and React state/context — even though they are rendered elsewhere in the DOM.
- They improve accessibility and user experience by ensuring elements like modals and popups behave as expected.