Articles → REACT.JS → Portals In React.Js

Portals In React.Js


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


  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 (
            {ReactDOM.createPortal(<ChildComponent/>, document.getElementById('child'))}            
                Sample Click Me Button</button>

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


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

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


Your Email Id  
Query/FeedbackCharacters remaining 250