DEV Community

Cover image for Learn how to use React Portals and improve your React development skills
Abhishek Rawe
Abhishek Rawe

Posted on

Learn how to use React Portals and improve your React development skills

What exactly the React Portals is ?

React Portal is a feature that allows you to render a component's content into a different part of the HTML document, outside of its parent component. It's useful when you want to display something like a popup or a tooltip, and you don't want it to be affected by the styles of the parent component.

Why we need React Portals ?

  • Avoid CSS conflicts: Sometimes, you may want to render a component's content (like a modal or a tooltip) outside of its parent component's DOM hierarchy to avoid CSS conflicts. By using a portal, you can ensure that your content is displayed in a separate part of the HTML document, without being affected by the parent component's styles.
  • Accessibility: Portals can be used to ensure that content is rendered in a specific part of the document for accessibility reasons. For example, you may want to render a dialog box in a specific part of the page to ensure that it can be read by screen readers.
  • Separation of Concerns: By using a portal, you can separate concerns between components responsible for data, logic, and layout, and components responsible for visual representation, without adding additional complexity.
  • Better Code Organization: React portals allow for better code organization by enabling you to decouple components that deal with data and functionality from components that are responsible for rendering.

How can I use React Portals?

Image description

Starter React Project:

what we do here a simple button that render after click on Button
and show some text on that same space we show our modal.

index.html

 import {useState} from "react" ;
 import "./App.css";
 function App() {
  const [show, setShow] = useState(false);
  return (
  <div className="App">
  <h2> Click to open Modal </h2>
  <button onClick = {() => setShow((s) => !s)}>Open Modal</button>
     {show && <h1>Modal will be rendered here </h1>}
  </div>
 );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Image description

When we go to the index.html file, we can see an empty div element with the id attribute set to "root". In index.js, we can see that React DOM is essentially injecting our entire app, along with all the components that we create, into this root div. We can confirm this by inspecting the "Elements" tab in the browser console, where we can see that our entire React app is rendered inside this root div.
Image description
Image description

React Portal Project :

Now what if we want to render a components that is outside our root div Then, React Portals come into the picture , Portal provides us a techinque to render our components outside its parents node.

Created a new file ie, modal.js

import React from "react";
function Modal({ show, closeModal }) {
  if (!show) return null;
  return (
    <div className="modal">
      <div className="overlay" onClick={closeModal}></div>
      <div className="content">
        <h2> Simple Modal </h2>
        <button onClick={closeModal}>Close</button>
      </div>
    </div>,
  );
}
export default Modal;
Enter fullscreen mode Exit fullscreen mode

In elements tab we see our modal is inside our div with className app. we can see it on our JSX but we want our modal to take 100 height and width of the viewport and appear above the all other componets.

so, in order to get this we need to render this model outside the parent div and for this we will be using React Portals.

Now for this we simply go to our index.html file and provide id here as

<body>
<div id="root"></div>
<div id="portal"></div>
</body>

In our modal.js we return ReactDOM.createPortal.
ReactDOM.createPortal, portal accepts two parameters first one is our JSX and 2nd one we need to print our div with that id of portal document.getElementById("portal")

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

function Modal({ show, closeModal }) {
  if (!show) return null;
  return ReactDOM.createPortal(
    <div className="modal">
      <div className="overlay" onClick={closeModal}></div>
      <div className="content">
        <h2> Simple Modal </h2>
        <button onClick={closeModal}>Close</button>
      </div>
    </div>,
    document.getElementById("portal")
  );
}

export default Modal;

We can see that our modal is being rendered correctly as it should be and if we actually inspect this and look at the actual element tree here you can see that our model has been rendered in this portal and not in the div with id of root.

Image description

Image description

We have to force react to render this model outside it parent by creating a portal to somewhere else and in our case the portal is this div which we have created . This is really a very handy features of react portal that it allows to render the child anywhere in the dom tree by also keeping the parents relationships intact between the elements so if you want to create any components like model, dialog, tooltip, alert which is always renders above its root elemetns make sure to use react portals.

Conclusion

Image description

React Portal is a feature in the React library that allows you to render a component's content into a different part of the HTML document, outside of its parent component. This can be useful for scenarios where you want to render a component's children outside of its parent's DOM hierarchy, such as when displaying a modal or tooltip. By using a portal, you can avoid CSS conflicts, improve accessibility, and better organize your code. Overall, React Portal is a powerful tool that can help you create more robust and flexible React applications.

Top comments (0)