Search⌘ K

Portals and Their Relationship to Their Parent Component

Explore the concept of React Portals by building a modal that renders outside its parent component’s HTML hierarchy. Understand how portals allow rendering in separate DOM nodes while keeping state and event functions connected to the parent component. This lesson helps you master conditional rendering and state management using portals in React.

We'll cover the following...

To further our understanding of portals, we are going to build a modal portal. The basis is formed by the following HTML:

HTML
<!doctype html>
<html>
<head>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"><!-- this is where our React App is located -->
</div>
<div id="portal"><!-- this is where the content of the portal will be stored -->
</div>
</body>
</html>

There are two divs in the example, one in which our application is rendered and another in which we render the portal.

This time, however, the modal will only open once a user has clicked a button. The portal will contain a button that allows the user to close the window. A state variable called ...