Open In App

What are portals in React and when do we need them ?

Improve
Improve
Like Article
Like
Save
Share
Report

In React 16.0 version, React portals were introduced. Portals in React come up with a way to render children components into a DOM node which typically occurs outside the DOM hierarchy of the parent component.

Before React Portals, It was very difficult to render the child component outside the hierarchy of its parent component. Every single React component in the React application falls under the root element.

But, the React portal concept provides us the ability to break out of this dom tree and render a component onto a dom node that is not under this root element. Doing so breaks the convention where a component needs to be rendered as a new element and follows a parent-child hierarchy. Portals are commonly used in modal dialog boxes, hover cards, loaders, and popup messages.  Below is the syntax of React portals. 

Syntax:

ReactDOM.createPortal(child, container)

Parameters:

  • child: It can be a React element, string, or fragment
  • container: It is a DOM node.

In the syntax above, we have two parameters the first parameter is a child that can be a React element, string, or fragment and the second one 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.

Advantages of React Portals

  • Event Bubbling inside a portal: Although we don’t render a portal inside the parent DOM element, its behavior is still similar to a regular React component inside the application. It can access the props and state as it resides inside the DOM tree hierarchy.
  • React portals can use Context API to transfer the data in components.

Steps to create React Application

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command.

cd foldername

Project Structure:

GFG

Example: This example creates a portal div to add a button. It shows welcome text when clicked.

Javascript




// Filname - App.js
 
import React, { Component } from "react";
import ReactDOM from "react-dom";
 
class Portal extends Component {
    render() {
        // Creating portal
        return ReactDOM.createPortal(
            <button>Click</button>,
            document.getElementById("portal")
        );
    }
}
 
class App extends Component {
    constructor(props) {
        super(props);
 
        // Set initial state
        this.state = { click: "" };
 
        // Binding this keyword
        this.handleClick = this.handleClick.bind(this);
    }
 
    handleClick() {
        // This will trigger when the button
        // inside Portal is clicked, It updates
        // Parent's state, even though it is not
        // rendered inside the parent DOM element
        if (this.state.click == "")
            this.setState((prevState) => ({
                click: "Welcome to gfg",
            }));
        else {
            this.setState({ click: "" });
        }
    }
 
    render() {
        return (
            <div onClick={this.handleClick}>
                <h1 style={{ color: "green" }}>
                    GeeksforGeeks
                </h1>
                <h2 style={{ color: "Green" }}>
                    {this.state.click}
                </h2>
                <Portal />
            </div>
        );
    }
}
 
export default App;


HTML




<!-- Filename - public/index.html -->
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8" />
    <link rel="icon"
        href="%PUBLIC_URL%/favicon.ico" />
 
    <title>React App</title>
</head>
 
<body
    style="text-align: center; margin: auto;">
 
    <div id="root"></div>
    <div id="portal"></div>
</body>
 
</html>


Steps to Run: Use this command in the terminal inside the project dirctory.

npm start

Output: This output will be visible on http://localhost:3000/ on the browser window.

Peek-2023-11-03-11-30

When do we need React Portals ?

We mainly need portals when a React parent component has a hidden value of overflow property(overflow: hidden) or z-index style, and we need a child component to openly come out of the current tree hierarchy. 

 Following are the examples when we need the react portals:

  • Dialogs
  • Modals
  • Tooltips
  • Hovercards

In all these cases, we’re rendering elements outside of the parent components in the DOM tree.



Last Updated : 06 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads