Learn how to use React Portals and improve your React development skills
Tags: javascript, react, frontend, interview
Published: 2023-02-26 21:55:47

# 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z1ujni4oe8jiit9iho6.gif)

### 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;
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6uraaas1h1mz8akuli6.gif)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acsgsfp2ngihrdfu2cws.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99k6lscp3f872kkqy4w7.png)

### 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;
```

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 <div id = "portal">

`<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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2f303o6r45p3bqt516ha.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3t6k7cuak8nh8wuilwm2.png)



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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xu0z69gc5xxsr7daagd.gif)


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.