React
  • Introduction
  • Getting Started
    • Introduction
    • Before you get started
  • 1. Fundamentals
    • Introduction
    • Rendering
      • JSX
      • Exercise
      • Solution
    • Components
      • Stateless
        • Exercise
        • Solution
      • Stateful
        • Exercise
        • Solution
      • Styling
        • Exercise
        • Solution
        • Using CSS Modules
    • Folder Architecture
  • 2. Intermediate
    • Lifecycle methods
    • Controlled and Uncontrolled components
    • Anti-patterns
    • Refs and the DOM
    • Lifting State Up
  • 3. Advanced Topics
    • Conventions
    • Reconciliation
    • Performance Optimizations
      • Avoiding Reconciliation
      • PureComponent
      • Avoiding inline lambdas
      • Development vs Production build
    • Context
  • 4. Advanced Patterns
    • Higher-order Components
    • Children as Function
    • Renderless Components
    • Portals
    • Error handling
  • Exercises
    • Introduction
    • 1. ProductList light
      • Step 1
      • Step 2
      • Step 3
      • Step 4
      • Extra
      • Solution
Powered by GitBook
On this page
  1. 4. Advanced Patterns

Portals

PreviousRenderless ComponentsNextError handling

Last updated 6 years ago

A typical use case for portals is when a parent component has an overflow: hidden or z-index style, but you need the child to visually “break out” of its container. For example, modals, popovers, and tooltips.

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

ReactDOM.createPortal(child, container)

The first argument (child) is any , such as an element, string, or fragment. The second argument (container) is a DOM element.

Usage Normally, when you return an element from a component’s render method, it’s mounted into the DOM as a child of the nearest parent node:

render() {
  // React mounts a new div and renders the children into it
  return (
    <div>
      {this.props.children}
    </div>
  );
}

However, sometimes it’s useful to insert a child into a different location in the DOM:

render() {
  // React does *not* create a new div. It renders the children into `domNode`.
  // `domNode` is any valid DOM node, regardless of its location in the DOM.
  return ReactDOM.createPortal(
    this.props.children,
    domNode,
  );
}
renderable React child