Articles → REACT.JS → Portals In React.Js
Portals In React.Js
Purpose
Click to Enlarge
Example
- Create a new node in index.html
- Create a component
- Use the portal to render the component
- Output
Create A New Node In Index.Html
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
Click to Enlarge