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'));
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:
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>
Through Javascript, we can do something like this:
const modal = document.querySelector('.modal');
const modalActivateButton = document.querySelector('.modal-activate');
modal.classList.remove('.hidden');
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 div
s, 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>
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')
);
}
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 π
Top comments (0)