Unlocking Hidden Realms: Exploring React Portals for Intuitive User Interfaces

Introduction

If you've ever wondered how Dr. Strange effortlessly travels through different dimensions, you'll love React Portals! Imagine them as your secret weapon for web design magic. With React Portals, you can do something similar – move elements across different parts of your web page without hassle.

As of now we are mounting our entire React App into root element which is a div with an id 'root'.

<body>
  <div id="root"></div>
</body>

But what if we want to make an another element having id 'portal' or any other name which is outside root element which is not included in the flow of React Component Hierarchy.

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

To make this task easier, ReactDOM Provides createPortal method, which takes two parameter child and container .

Syntax:

ReactDOM.createPortal(child, container)

createPortal

Here the first parameter is a child which can be a React element, string, or a fragment and the second parameter is a container which is the DOM node (or location) lying outside the DOM hierarchy of the parent component at which our portal is to be inserted.

<body>
  <div id="root"></div>
  <div id="portal"></div> // I want to insert Portal Component here
</body>
import React from "react";
import ReactDOM from "react-dom";

const Portal = () => {
  return ReactDOM.createPortal(
    <h1>This is Portal Element</h1>,
    document.getElementById("portal")
  );
};

export default Portal;

Output:

Usage of Portal

Generally we are using portals to make sidebar or modal which is independent from Component Hierarchy.

0
Subscribe to my newsletter

Read articles from Niket Kumar Mishra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Niket Kumar Mishra
Niket Kumar Mishra

I am a Frontend Web Developer and a self-Learner. I want to utilize my skills for Development. I want to work in a competitive environment where I can enhance my skills along with facing the new Situations, learning new things, Exploring the world.