What Is React Teleportation?
Transporting React components to other React components with portals
Have you ever wanted to render a React component in a totally different part of your app? In this article, I will show you how to do that while still having control of it within the first component.
If you look at the example below we have a
PortalIn component that will take whatever is passed into it and render it out where the
PortalOut component is. To make this work, the two React components need to have the same
portalType (I’m using
headerPortal for the identifier). They also need to be wrapped within the
Take a look at the animation below. There is a portal in the header, to the left of the notification bell. There are a few things to keep in mind:
- The Welcome page does not send anything to the header portal.
- The Dashboard page sends a counter button into the header portal that updates the count on the page.
- The About page sends a call me button into the header portal.
We are going to use the React Context API to create a
PortalProvider with two other React components
Let’s start with the
PortalOut component first. You will notice we have access to a
PortalContext and on there is a
PortalOut components with the help of the
portalType. When the
PortalOut renders it will either render a React component from the
portalMap, or nothing because there is no match for the
Looking at the
PortalIn component, you can see we access the
removePortalItem functions from the
- Within React.useEffect we send the
addPortalItemfunction where it is added to the
portalMapobject that is in
- Also notice in the
PortalIncomponent is unmounted within the React app. This removes the component from the
- Lastly, notice we return
nullso nothing is rendered because we don’t want anything to be displayed in this component. That is the job of the
Finally, let’s look at how we use React Context Provider to create our
PortalProvider. We use React.useState and Map to hold onto holds key-value pairs which is the
portalType and the
component we passed in via the React.children and
Hopefully, this makes sense but if you are wondering why we need to create a
new Map each time, it’s because we need
useState to trigger an update whenever the
removePortalItem functions are called.