An Introduction to React Portals

akashshyam

Akash Shyam

Posted on March 18, 2021

An Introduction to React Portals

The first thing that comes to my mind when thinking about the word portals is teleporting. We are able to teleport outside our parent-child hierarchy and create a sibling element. Today I'll be talking about React Portals. Before actually explaining what a portal is, let me tell you what do portals solve.

The Problem

Any basic react app has a div in the HTML file and a javascript file has the following code:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

ReactDOM converts the App component into HTML, CSS and Javascript and injects it into the selected element.

By default, most react apps have the following hierarchy:

Screenshot 2021-03-18 at 16.46.59

We all embed our components into the <App /> component. When we try to build a modal component, we want it to cover the whole page and nothing else should be clickable. In normal HTML pages, we would do something like this:

<div class="content">
  <!-- button to open modal -->
  <button class="modal-activate">Open Modal</button>

  <!-- content of page goes here -->
</div>

<div class="modal hidden">
  <!-- Modal goes here -->
</div>
Enter fullscreen mode Exit fullscreen mode

Through Javascript, we can do something like this:

const modal = document.querySelector('.modal');
const modalActivateButton = document.querySelector('.modal-activate');

modal.classList.remove('.hidden');
Enter fullscreen mode Exit fullscreen mode

We can add some CSS to set the display to none in the hidden class... you get the idea.

As you can see, we have to sibling divs, one for the modal and the other for the rest of the content. Now, let's see how to do the same in React.

Portals

Portals basically allow us to add a component to a sibling div of the root div. First, we need to add another div in our index.html file.

<div id="root"></div>
<div id="modal"></div>
Enter fullscreen mode Exit fullscreen mode

Let's create a new component called Modal:

import React from 'react';
import ReactDOM from 'react-dom';

export default function Modal({ title, content, actions, onDismiss }) {
    return ReactDOM.createPortal(
        <div>
                  // Content for modal goes here
                </div>,
        document.querySelector('#modal')
    );
}
Enter fullscreen mode Exit fullscreen mode

Now we can add any buttons/content into the div.

That's it, we're done. A sibling div is created! That's all for now. I hoped you like this simple post, if you did please like it and follow me. Bye πŸ‘‹

πŸ’– πŸ’ͺ πŸ™… 🚩
akashshyam
Akash Shyam

Posted on March 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related