Understanding React Portals: Simplified Explanation with Code

The Syntax NodeThe Syntax Node
4 min read

React Portals are a feature introduced in React 16 that allow developers to render components outside of their current DOM hierarchy. While a component is logically part of its parent, portals enable it to appear elsewhere in the DOM. This is especially helpful when building modals, pop-ups, or tooltips.


What Are React Portals?

By default, React components render as part of their parent’s DOM structure. Sometimes, though, you may need a component to break out of its usual hierarchy. For example, you might want a modal to display above the rest of your application UI, even if its component is deeply nested.

React Portals make this possible. Using ReactDOM.createPortal, you can render a component into a DOM node that’s outside the root element where your React app is mounted.


How to Create a Portal

The process of implementing a portal involves three key steps:

  1. Create a target DOM node in your HTML where the portal’s content will render.
  2. Use the ReactDOM.createPortal method to render your component into the target node.
  3. Ensure the portal is used correctly within your application.

Step 1: Set Up the Target DOM Node

Ensure that your main HTML file contains a container for the portal. This is typically a div outside your root app container.

<!-- index.html -->
<body>
  <div id="root"></div>
  <div id="portal-root"></div>
</body>

Here, #portal-root will serve as the destination for your portal content.


Step 2: Create the Portal Component

Build a React component that uses ReactDOM.createPortal to render its children into the target DOM node.

// Modal.js
import React from "react";
import ReactDOM from "react-dom";
import "./Modal.css"; // Optional styling for the modal

const Modal = ({ isOpen, onClose, children }) => {
  if (!isOpen) return null;

  return ReactDOM.createPortal(
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        {children}
        <button className="close-button" onClick={onClose}>
          Close
        </button>
      </div>
    </div>,
    document.getElementById("portal-root")
  );
};

export default Modal;

Explanation:

  1. ReactDOM.createPortal takes two arguments:
    • The JSX you want to render.
    • The DOM node where it should render (in this case, #portal-root).
  2. The modal includes an overlay (modal-overlay) that closes the modal when clicked outside of the content.

Step 3: Use the Portal in Your App

In your main app, you can now use the Modal component and control its visibility using state.

// App.js
import React, { useState } from "react";
import Modal from "./Modal";

function App() {
  const [isModalOpen, setModalOpen] = useState(false);

  return (
    <div className="App">
      <h1>React Portals Example</h1>
      <button onClick={() => setModalOpen(true)}>Open Modal</button>

      <Modal isOpen={isModalOpen} onClose={() => setModalOpen(false)}>
        <h2>This is a modal</h2>
        <p>You can click outside or use the close button to close it.</p>
      </Modal>
    </div>
  );
}

export default App;

Step 4: Add Some Styling

Let’s add some basic CSS to make the modal look presentable.

/* Modal.css */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  max-width: 500px;
  width: 100%;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.close-button {
  margin-top: 15px;
  padding: 10px 15px;
  background: #ff4d4d;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.close-button:hover {
  background: #ff1a1a;
}

How It Works

  • Breaking Out of the DOM Hierarchy: Even if the Modal component is used deep inside the component tree, it renders outside the main app's root container in #portal-root.
  • Interaction Management: Clicking outside the modal content closes it. The click event on the overlay is stopped from propagating to ensure the content inside behaves as expected.

When to Use Portals

Portals are especially useful for:

  • Modals/Dialogs: Displaying content that should visually appear above everything else.
  • Tooltips: Rendering tooltips outside of their parent component’s boundaries.
  • Dropdowns: Handling dropdown menus that may otherwise be clipped by overflow: hidden or z-index issues.

Conclusion

React Portals provide an elegant solution to render components outside their parent’s DOM hierarchy without breaking React’s declarative nature. By understanding how to use ReactDOM.createPortal, you can enhance your UI with features like modals and tooltips, ensuring they work seamlessly across your app.

0
Subscribe to my newsletter

Read articles from The Syntax Node directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

The Syntax Node
The Syntax Node

I am a JavaScript Full Stack Developer with expertise in front-end frameworks like React and Angular, and back-end technologies such as Node.js and Express.