How To Create Portal In ReactJS

Hello Developers, Today we will learn how to Create a portal in ReactJs.

Before moving toward Demo let us understand the use of the portal in React.

  • Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
  • Portal supports server-side rendering

Steps to create a portal

Step-1: Create an element outside the root element in index.html

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <div id="portal-root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>

Step-2: Create PortalDemo.js Component 

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

const PortalDemo = () => {
  return ReactDOM.createPortal(
    <h1 style={{textAlign :'center'}}>PortalDemo</h1>,
    document.getElementById('portal-root')
  )
}

export default PortalDemo

Step-3: Add PortalDemo.js into App.js

import React, { Component } from 'react'
import PortalDemo from './Components/PortalDemo'

 class App extends Component {
  render() {
    return (
      <div>
        <PortalDemo />
      </div>
    )
  }
}

export default App

Here is an output where you can verify that we have rendered children into a DOM node that exists outside the DOM hierarchy of the parent component.

Hoping you have upgraded your knowledge. Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories