
This article will cover -
- Basic intro to Portals in React.js
- Why & How to use react portals
React Portals
Renders react components outside of root DOM element
What is a Portal
React renders all its components inside a single root DOM element (ideally of id = "root").
If instead, we have a use-case where we want to render a component outside of this root element, we use a concept calledReact Portals.
How to create Portals
Ideally, to bootstrap a react app, we use ReactDOM.render method to render our react app to root element.
<divid="root"></div>
ReactDOM.render(<SomeReactComponent/>,document.getElementById('root)
Similarly, To create a portal we use ReactDOM.createPortal method which takes two parameters
- React Component or JSX
- HTML DOM element
<divid="root"></div><divid="portal"></div>
ReactDOM.createPortal(<h1>Portal goes here</h1>,document.getElementById('portal'))
Why to use React Portals
We can use Portals while creating a Modal or Popup as these occupy space outside of the normal element ordering/stacking. Modals sometimes cover the whole page for example take a look at the below code -
<Wrapperstyle={{maxWidth:'250px',zIndex:1,position:'relative'}}><Modalopenstyle={{zIndex:1000,postion:'fixed',top:0,left:0}}><p>Some content inside Modal</p></Modal></Wrapper><OtherWrapperstyle={{zIndex:100}}><div>some other content</div></OtherWrapper>
As per the example above,Modal is being rendered inside aWrapper that has max-width limitation and a z-index set to 1. That means even though Modal has a z-index of 1000, it cannot be on top of everything becauseOtherWrapper has a higher z-index thanWrapper.
Hence, Modal(z-index=1000) will be still under OtherWrapper(zIndex=100) as Modal is inside Wrapper(z-index=1).
To overcome these kinds of issues, we can implement a Portal to render Modal -
<body><divid="root"></div><divid="portal-root"></div></body>
return ReactDOM.createPortal(<div> Modal content goes here</div>, document.getElementById('portal-root'))
This will render the Modal component insideportal-root DOM element outside the root element. However, this is will be kept as usual in React component tree & events are listened & executed as before.
Thanks for checking!
Stay safe :)
References:
https://reactjs.org/docs/portals.html
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse