Step by Step to Create React portal to Display Our App

React Create Portal

React portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. What does that mean well so far we have had one DOM element in our HTML that we were mounting the React application. In the DOM tree, every single React component in our application falls under the root element. That is the div element with ID is equal to the root. What reacts portals provide is the ability to break out of this DOM tree. So, you can render a component onto a DOM node that is not under this root element. Let me show you how to create and use react portal with step by step simple example.

  1. To add a DOM node that falls outside the root elemnt. So, in index.html we added another <div> tag with id name “portal-root”.
    index.html

    <div id="root"></div>
    <div id="portal-root"></div>
  2. We should create a new functional component namely PortalDemo() in the new file of “PortalDemo.js”. In JSX, we simply added a heading that says “Portals Demo”.
    const PortalDemo = () => {
        return(
            <div>
             <h1> Portal Demo</h1>
            </div>
        )
    }
  3. After that, we include the PortalDemo() component in the app component.
  4. See the output, our expected output is displayed successfully.react create portal
And see below the inspect element of our output, the element falls under the “root” element and not under the “portal-root” element because we rendered it in “root” Id. Let’s change that:
  5. ┬áTo change that, we will use “ReactDom.createportal” method to insert the PortalDemo component under the “portal-root” node. So, in the PortalDemo.js file, we need to import the “ReactDom” package. Then in the render method instead of simply returning the JSX, we are going to return “ReactDom.createportal” method. And that method takes two parameters, first parameter is JSX you want to return which is the heading “portal Demo”. The second parameter is the DOM node to mount the element. So, we have passed “document.getElementById(‘portal-root’).
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const PortalDemo = () => {
    return ReactDOM.createPortal(
    <h1>
    Portal Demo
    </h1>,
    document.getElementById('portal-root'))
    }
  6. Now see our output is displayed under the “portal-root” element successfully.react create portal
READ ALSO  What are the Lifecycle Method in React | Wonder Develop

 

Leave a Reply