Articles → REACT.JS → Portals In React.Js

Portals In React.Js






Purpose




Picture showing the default rendered HTML when everything is included in the root element
Click to Enlarge




Example




  1. Create a new node in index.html
  2. Create a component
  3. Use the portal to render the component
  4. Output



Create A New Node In Index.Html




Picture showing creating a new child div above the root div
Click to Enlarge


Create A Component




import React, { Component } from 'react';
import ReactDOM from 'react-dom'




class ChildComponent extends React.Component {
    render() {
        return <h2>This is child component</h2>;
    }
}

export default ChildComponent



Use Portal To Render The Component




import React from 'react';
import ReactDOM from 'react-dom'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import ChildComponent from './gyan.js';




const Home = () => {    


    return (
        <React.Fragment>
            {ReactDOM.createPortal(<ChildComponent/>, document.getElementById('child'))}            
            <button>
                Sample Click Me Button</button>

        </React.Fragment>
    );
}
ReactDOM.render(<Home />, document.getElementById("root"));





Output




Picture showing the output of portals in react.js
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, October 28, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250