DEV Community

muneebejazz
muneebejazz

Posted on

React Portals

Raact portals provide a way to render children into a DOM node that exists parent DOM hierarchy.

In react app the div with id root is the entry point, and all the DOM elements exits under root element.

React Portal provide ability to break out of this root and exists anywhere outside the scope of root div.

we will use ReactDom.createPortal(component, element)

we can create a PortalDemo functional component

import React from 'react'
import ReactDom from 'react-dom'
export Default function PortalDemo(){
   return ReactDom.createPortal(
       <h1>Portals Demo</h1>,
       document.getElementById('portal-root')
   )
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)