A simple guide to React portal
Discover how to benefit from React portal and use it within your project
Before getting started, let’s have a quick talk about what React portal is.
React portal has been added to React back in version 16.0 and has been a life-changer for a lot of developers.
It indeed made it easier for developers to manage dialogs and modals and instantiate components outside of their hierarchy.
How does it work
Portal uses a DOM element as a target to append your component as a child of it. But the instantiated component is still part of your tree! This means that contexts and states from the parents are accessible from the child component.
Before being able to use Portal, you need to be able to target a DOM element. You can use a method like Document.getElementById
and simply use the result as a new parent for your component.
Once the new element is ready to be used, all you have to do is import createPortal
from ReactDOM and call it giving the React component to instantiate and the DOM element: createPortal(child, DOMElement)
Let’s do it!
Let’s create a simple React project. I’m going to use Codesandbox and a simple React template.