How you can use React Portals

Another interesting pattern for react component reuse are so called react portals which let you pretend that and random DOM node is part of your component children.

Essentially what happens with the react portal is that you render something called react create portal as part of your component. Those children can be any random DOM node. You pass basically a DOM node that's over here into your component that's over here.

It's kind of hard to explain. So let me just show it to you with some code.

The normal use case for a react portal is something like a modal or something like a tool tip.

To experiment with portals we are first going to create a div that's going to hold our status RAF to it which we're going to put into our app state and then past all of our buttons with the context API. We're then going to use a status portal which is going to render as a child of the button, but actually in the status div and that's going to show off how portals work. It's a bit contrived, but we do what we can.

Here we're going to say status RAF key 8 RAF. And we then render it outside of the context just to prove a point. Status RAF.

Because we have an app context provider this is automatically passed to all of our buttons. In our button bin, import the status portal. This is where the real magic of portals happen. Render our portal if the button was clicked. If it wasn't clicked then we don't render it. It's going to show up in a completely different part of the app because it's going to be using react portals.

We now define our status portal as a normal react component. In this render method is going to return an app context consumer. Which is going to get our status RAF in it from state. And if status raf.current is already defined, which at first it isn't, then we render re add the DOM create portal. Portal is going to render a paragraph that says clicked our current label and that label is getting rendered into the current DOM node that status RAF is pointing to.

Now when I click alert hide, it first alerts the alert box that we were building last time. Renders status here called clicked alert high. And if you look at out button, its rendering a status portal here, but that status portal is actually rendered somewhere else. That can come in handy in some cases.

Know someone who wants to learn React and its whole ecosystem? Share 👇