An explanation of portals in React.
Join DevzConnect — where devs connect, code, and level up together. Got questions? Stuck on a bug? Or just wanna help others crush it? Jump in and be part of a community that gets it
Welcome back to DevzConnect — where devs connect, code, and level up together. Ready to pick up where you left off? Dive back in, ask questions, share wins, or help others crush their goals!
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
n React, portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component. This allows you to break out of the normal component tree structure and place elements in different parts of the DOM, which can be especially useful for modals, tooltips, or other UI elements that need to visually appear outside their normal container but still be part of the React component tree.
Why Use Portals?
Portals allow for rendering UI elements outside of their normal DOM hierarchy, which is often needed for things like:
These elements need to be visually rendered outside their parent component for proper positioning and layering (especially if the parent has overflow hidden or other styling constraints). However, they still need to be part of the component’s state and lifecycle.
How Portals Work in React:
React provides the
ReactDOM.createPortal()
method to create a portal.Syntax:
ReactDOM.createPortal(child, container)
child
: The React component or element that you want to render.container
: The DOM node where the child element will be rendered.Example of Using Portals:
Let’s say you want to create a modal that should appear at the top of the document, outside the usual flow of your app, but still be part of the React tree for easy state management.
Now, in your index.html file, you need to have a
div
with theid="portal-root"
:Then, in your app, you can render the
Modal
component like this:Why Use Portals?
Positioning:
Avoid DOM Overflow Issues:
overflow: hidden
or other constraints, using portals can help ensure your modals or other elements are displayed correctly without being clipped.Z-Index Management:
div
outside of the main app container.Important Notes:
Summary:
ReactDOM.createPortal(child, container)
and specify a DOM node (container
) where the child should be rendered.