React Portal Tutorial

React Portal is a very cool feature of React 16 which allows you to render React components independent of the component heirarchy. The component can rendered in any arbitrary container outside the React component tree. This comes in handy when rendering modals or tooltips in your React app that can better be better managed in a separate sub tree of the dom.

Here is a higher order component I've created that renders any children passed into it in the selector element. All you do is call createPortal and pass the children along with the target node. The function signature is very close to ReactDOM.render.

// Portal.js

import React, { Component } from "react";
import ReactDOM, { createPortal } from "react-dom";

export default class Portal extends Component {
  render() {
    const { selector } = this.props;
    return ReactDOM.createPortal(
      this.props.children,
      document.querySelector(selector)
    );
  }
}

Now all you do in your app is render the Portal and the child nodes. Despite being out of the DOM hierarchy, thanks to React your JavaScript events will work exactly as they would've in it.

// app.js

import React, { Component } from "react";
import ReactDOM, { createPortal } from "react-dom";
import Portal from "./Portal";

class App extends Component {
  render() {
    return (
      <div class="app-container">
        <Portal selector={".nav"}>
          <button>Menu</button>
        </Portal>
        <div class="app-content">
          Hello World
        </div>
      </div>
    )
  }
}

ReactDOM.render(App, document.querySelector(".app"))

Here is the html file for referencing the selectors used in the example.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Portal example</title>
</head>
<body>
  <div class="nav"></div>
  <div class="app"></div>
</body>
</html>

Hope creating portals in React is easy for you too after going through this tutorial. Have a great day!