In this blog post, I will explain the react portal, you must be thinking about what this react js portal is, well react portal we use to display any text or HTML element outside the root element.
As we know all the react Js user interface parts render inside a div with root id, but what if we don’t want our new HTML element to be displayed inside the root element?
There can be many use cases for this, for example in the case of modals or popups, these elements overlay the parent elements and that is not a proper way to align HTML elements.
So it’s better to separate these from the parent root element, let’s understand this through the code.
React js portal
First of all, you have to create a div with some id inside the index.html file which you can find inside the public folder. here you will see a div with root id, which is basically the parent div for rendering react application.
Here I am creating a div with an id called “other-div“.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="other-div"></div>
<div id="root"></div>
</body>
Now inside the App.js file, we will import ReactDom for handling elements, and this ReactDom has a function called createPortal which helps to assign HTML elements to other div elements outside of the root element.
Here is the complete code where we are using ReactDome.createPortal function to assign <OtherDiv /> component value to division with id “other-div”.
import './App.css';
import ReactDom from 'react-dom';
function App() {
const OtherDiv =()=>{
return <h2>Hello, text is displaying inside other div</h2>
}
return (
<React.Fragment>
{ReactDom.createPortal(<OtherDiv />,document.getElementById('other-div'))}
</React.Fragment>
);
}
export default App;
OtherDiv is a method which is returning a text message.
Let’s check the output for this code.
In the above image, you can see the output text is coming inside the other-div element, not inside the root div, so you can use createPortal for this.