Introduction:

This article explains about Portals in React.

What is a Portal?

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. Typical use cases for Portals are Modals/Dialogs, pop-ups, tooltips, global message notifications etc.

Reference: React Documentation.

Why to use Portals?

A Portal can be anywhere in the DOM tree but behaves like a normal React child. So, all the powers of React component apply to Portals as well. Some of the examples are as follows:

How to use Portals?

Basic implementation of Portals:

import React from "react";
import { createPortal } from "react-dom";

const modalRoot = document.getElementById("modal");

class Modal extends React.Component {
  constructor(props) {
    super(props);

    this.el = document.createElement("div");
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    //To avoid memory leaks we perform cleanup before Unmount
    modalRoot.removeChild(this.el);
  }

  render() {
    return createPortal(this.props.children, this.el);
  }
}

export default Modal;

Demystifying the above code snippet.

Modal>
  <p>This would send an Email to AK. Are you sure?</p>
  <div className="buttons">
    <button onClick={this.toggleModal}>Yes</button>
    <button onClick={this.toggleModal}>No</button>
  </div>
</Modal>

DOM structure from Chrome Dev tools

Event bubbling with Portals:

Render block from App.js:

render() {
  return (
    <div className="App" onClick={this.handlePageClick}>
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>AK at BeautifulCode is good at React!</p>
        <p>
          {" "}
          To ask him questions please{" "}
          <button onClick={this.toggleModal}>Cick here!</button>
        </p>
        <p>Total number of Page Clicks so far {this.state.pageClicks} </p>
      </header>
      {this.state.showModal && (
        <Modal>
          <p>This would send an Email to AK. Are you sure?</p>
          <div className="buttons">
            <button onClick={this.toggleModal}>Yes</button>
            <button onClick={this.toggleModal}>No</button>
          </div>
        </Modal>
      )}
    </div>
  );
}

Observations from above snippet:

Source Code:

Please find the source code at https://github.com/abhilash4252/React-Portals-Demo/

When to use?