Portals in React JS

React V16 gave us amazing features like new return types(fragments and strings), better error handling, portals etc., In this article, I am going to explain what is react portal, how it is different from normal react component and where react portals are used in real world applications.
What is React Portal?
Generally, React renders the component as a child to the parent in which it is used. Whereas, portals in react gives developer an advantage to add a component outside the current DOM hierarchy by maintaining the event bubbling and state management.
Traditional component
The above react component when rendered in browser, the DOM hierarchy will be like this,

Portal Component
The above react component which uses portal to render the children looks like this in DOM hierarchy,

How Portals are created
React portals are created using createPortal method of ReactDOM.
ReactDOM.createPortal(children, rootNode);React portals are used in certain real world scenarios like creating components for modal pop ups or toast messages.
Coming Soon: Creating a generic Modal component using React Portals.
The code samples used in this article can be downloaded from here.
