How to Create Modal Popup using React Portal

Gaurav Goyal
Nov 1 · 2 min read

By default, React renders the entire application under a root DOM Node. If you are familiar with React, you will know that the entire application is a component, usually known as <App/>. This App component gets appended to child div which is also called #root. Any changes inside the application will re-render the complete DOM Node (i.e. root node). This gets trickier when our components are deeply nested.

To avoid this, React Portals API provides a way to render children into a DOM Node that exists as a sibling of DOM Hierarchy / Root Node of the parent element.

As per official React docs

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component

The code convention to use React Portal is :

ReactDOM.createPortal(children, container)

In the above code snippet, the first argument is children which can be any component that we want to wrap in a portal, the second argument is a container that is a portal node.

The index.html as shown below, here we have created a separate div with id portal which will contain the portal component.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<div id="portal"></div>
</body>
</html>

As we can see in our example below, when we are clicking the delete button it is adding the modal in the portal node without disrupting the root node.

React Portal API improves performance when we have nested components by just rendering the #portal node instead of #root node (i.e. App Component)

You can check the code from the below URL.

https://github.com/ergauravgoyal/portal-app

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade