Everyone knows react is a powerful tool for web development that comes with a lot of great features. Today I want to talk about react portals and going over a few things like what is a portal? Why use a portal? How can it help me? With that out of the way let get to and start with what a react portal is.
What is React Portals?
A react portal is a feature that allows users to render child elements into DOM nodes outside of the Dom hierarchy of the parent component. Portals are a way to remove the constraints on the child elements position. Normally the child’s position is based on the parents’ position and the parent is treated as a container for the child element. But with portals, I can break through that container and put it anywhere.
Why use Portals?
Portals are good because they can help you achieve the page structure you want without having to make massive component changes. So you can keep your component hierarchy the same. You want to use portals when the parent component has overflow: hidden or z-index style and need the child element to break out of the container. Some examples of this would be a notification, dialog, tooltips, etc.
Event bubbling Trough portals
Portals are treated as like a normal and behaves like a normal react child. It’s like they were rendered in the same DOM tree. I think the Reacts docs words it best.
Even though a portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. Features like context work exactly the same regardless of whether the child is a portal, as the portal still exists in the React tree regardless of position in the DOM tree. -Reacts docs
This has been react portals I was going to add how to implement it but I don’t want this blog to be too long. So next week I’ll be writing a tutorial on how to implement portals into your code. I hope you found this blog helpful. As always I’ll be linking links I found helpful while researching down below.