Part two Portals

Daniel Cooper
3 min readDec 7, 2020

Hey, guys this week’s blog will be a follow-up on last week’s where we went over what react portals are, why/when we use them, and how they work. This blog will cover how to use and implement react portals.

Step one: Go into the HTML file and find where the ‘Root’. Then add a div on the same level as the ‘root and give it an id.

What you should be looking for.
What we added

This is the DOMnode that we will be sending out pop, modal, etc. so that it can escape the CSS of the parent element. Like z-index etc.

Step Two: Go to the component that is being sent over to the newly created DOMnode. Here we are going to do two things.

  • Import ReactDom from ‘react-dom’
  • Call the ‘createPortal’ function

The ‘createPortal’ function takes in two params the first param is whatever we want to render. The second param is the DOMnode we will be mount to. Examples below:

Example#1

Return ReactDom.createPortal(  <div>    This is what I want to mount  </div>,
document.getElementById(‘id)
)

Example#2

Shows waht my code looks like

Now that we know how to use and implement react portals here are two pictures one of before the portal and one for after the portal.

Before we used portals
After the portal

So in the first picture the green bar is not being covered by the shadow. This is because the modal is a child of app and apps z-index is 1 where the green bar has an z index of 2. The CSS for the modal sets the z-index equal to 1000. This mean once we get the modal on a different DOMnode it will be above anything with and z-index lower then 1000.

This is the end of a two part blog about portals. I hope you found this blog helpful or were able to at least take something from it. I will be linking the videos and articles I used while researching portals.

Helpful links:

--

--