React Portals: Rendering Components Outside the Standard Component Hierarchy

Learn how to use React Portals to render components in a different location in the DOM than their parent component. This tutorial explains the functionality of `ReactDOM.createPortal()`, demonstrates its use in creating overlays and modals, and highlights its advantages for building complex and flexible user interfaces.



React Portals: Rendering Outside the Component Hierarchy

What are React Portals?

React portals (introduced in React 16.0) let you render a component's output into a different part of the DOM (Document Object Model) than where the component itself is located. This is useful for placing components that need to sit on top of other elements, regardless of their position in the component tree. Before React 16, achieving this was significantly more complex.

Syntax

The core function for creating portals is ReactDOM.createPortal():

ReactDOM.createPortal()

ReactDOM.createPortal(child, container)

child is the component or element you want to render, and container is the DOM element where you want it to appear.

Example: Before and After Portals

Without portals, a child component is rendered within its parent's area in the DOM:

Rendering without Portals

render() {
  return (
    <div>
      {this.props.children}
    </div>
  );
}

With portals, you can render the child into a different location, specified by a DOM element (e.g., with an ID):

Rendering with Portals

render() {
  return ReactDOM.createPortal(
    this.props.children,
    document.getElementById('myPortal') // The target DOM element
  );
}

Key Features of React Portals

  • Uses the official React API.
  • Works with React versions 15 and above.
  • By default, renders into document.body.
  • Supports custom target DOM elements.
  • Supports server-side rendering.
  • Supports returning arrays of elements (no need for extra wrappers).
  • Clean and efficient; no unnecessary DOM manipulation.
  • No external dependencies.

When to Use React Portals

Portals are ideal for:

  • Modals (popup dialogs)
  • Tooltips
  • Floating menus
  • Widgets

Installation

Install using npm:

Installation Command

npm install react-portal --save

Example Project Setup

(A simplified example showing the basic structure. You would need to create the files mentioned)

In App.js:

App.js

import React from 'react';
import PortalDemo from './PortalDemo';

const App = () => (
  <div>
    <PortalDemo />
    <div id="portal-root"></div> {/* Target for the portal */}
  </div>
);

export default App;

In PortalDemo.js:

PortalDemo.js

import React from 'react';
import ReactDOM from 'react-dom';

const PortalDemo = () =>
  ReactDOM.createPortal(
    <div>Portals Demo</div>,
    document.getElementById('portal-root')
  );

export default PortalDemo;

In index.html (you'll need the portal-root div):

index.html

<div id="root"></div>
<div id="portal-root"></div>

Next Topic: React Error Boundaries