React Portals: What they are and How to use them
July 29, 2018
Welcome back guys, on our theme of learning React concepts today I wanted to discuss React Portals. What they are, why used them and then I give you examples and resources to help you understand them better. If you have any questions feel free to reach out to me on twitter.
What are React Portals?
According to the React Documentation “Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.” If your not too familiar with React you might not have any idea what that means. In simpler terms in React you usually have this code (usually in a file called index.js):
If you have never seen this file, I wouldn’t be surprised this is generated by create-react-app and you never usually need to edit this file. In very simple terms you are telling React(specifically ReactDOM to take your entire application (
Now, where do portals come in? Instead of just having one
you create anotherWhy Portals?
Portals are extremely useful for things such as models, dialogs or even iframes, i.e when you need to take up the entire screen or mess with the z-index. Before Portals, this sort of thing was very hard to do in React and it cannot be easily done using a regular component as it would just appear in the regular React tree (as a child of a bunch of other elements).
Creating and using a Portal
As stated earlier to create a portal we need to start by adding a new
Now we have an outlet for the portal, we need to create a React Portal in Javascript using ReactDOM.createPortal(). We are going to do this in a Portal component in which we can reuse to teleport any element into our portal. Here is what the Portal component looks like with comments in the code explaining what each line is:
We now have an outlet for our portal and a Portal component to transport/portal our elements into, its time to actually use the Portal! I am going to use a HTML Modal for this example, I am just taking the example from Bootstrap:
That is the Modal component created, now its time to bring together the Modal and the Portal. Here is how we do that:
You can see the portal was able to display completely over the rest of our application making for a better user experience. That is the power of portals and as stated before doing this in React was unnecessarily complicated.
Resources
I hope you enjoyed my walkthrough of creating a Portal, if you want to dig deeper into Portals here are a few more resources.
LevelUpTuts Tutorial on Portals
That is it for today guys, I hope you enjoyed this post on React Portals, as stated if you have questions or queriesfeel free to reach out to me on twitter.