Sitemap
Aman Rathore

Aman Rathore

👋 Hello, I'm Aman Rathore, a passionate web developer with 5 yrs of experience in crafting user-centric, responsive websites and web applications.

React Portal

1 min readDec 30, 2022

--

What is React Portal

The React 16.0 version introduced React portals in September 2017. A React portal provides a way to render an element outside of its component hierarchy, i.e., in a separate component.

Get Aman Rathore’s stories in your inbox

Join Medium for free to get updates from this writer.

Before React 16.0 version, it is very tricky to render the child component outside of its parent component hierarchy. If we do this, it breaks the convention where a component needs to render as a new element and follow a parent-child hierarchy. In React, the parent component always wants to go where its child component goes. That’s why React portal concept comes in.

ReactDOM.createPortal(child, container)  

Here, the first argument (child) is the component, which can be an element, string, or fragment, and the second argument (container) is a DOM element.

Features

  • It uses React version 16 and its official API for creating portals.
  • It has a fallback for React version 15.
  • It transports its children component into a new React portal which is appended by default to document.body.
  • It can also target user specified DOM element.
  • It supports server-side rendering
  • It supports returning arrays (no wrapper div’s needed)
  • It uses <Portal /> and <PortalWithState /> so there is no compromise between flexibility and convenience.
  • It doesn’t produce any DOM mess.
  • It has no dependencies, minimalistic.

When to use?

The common use-cases of React portal include:

  • Modals
  • Tooltips
  • Floating menus
  • Widgets

Installation

We can install React portal using the following command.

  1. $ npm install react-portal — save

--

--

Aman Rathore
Aman Rathore

Written by Aman Rathore

👋 Hello, I'm Aman Rathore, a passionate web developer with 5 yrs of experience in crafting user-centric, responsive websites and web applications.