DEV Community

Hari Kotha
Hari Kotha

Posted on

React Portals: Intro

React portals image

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 called React Portals.

How to create Portals

Ideally, to bootstrap a react app, we use ReactDOM.render method to render our react app to root element.

<div id="root"></div>
Enter fullscreen mode Exit fullscreen mode
ReactDOM.render(<SomeReactComponent />, document.getElementById('root)
Enter fullscreen mode Exit fullscreen mode

Similarly, To create a portal we use ReactDOM.createPortal method which takes two parameters

  1. React Component or JSX
  2. HTML DOM element
<div id="root"></div>
<div id="portal"></div>
Enter fullscreen mode Exit fullscreen mode
    <h1>Portal goes here</h1>,
Enter fullscreen mode Exit fullscreen mode

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 -

<Wrapper style={{ maxWidth: '250px', zIndex: 1, position: 'relative' }}>
    <Modal open style={{ zIndex: 1000, postion: 'fixed', top: 0, left: 0 }}>
        <p>Some content inside Modal</p>

<OtherWrapper style={{ zIndex: 100 }}>
    <div>some other content</div>
Enter fullscreen mode Exit fullscreen mode

As per the example above, Modal is being rendered inside a Wrapper 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 because OtherWrapper has a higher z-index than Wrapper.

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 -

    <div id="root"></div>
    <div id="portal-root"></div>
Enter fullscreen mode Exit fullscreen mode
return ReactDOM.createPortal(
        Modal content goes here
Enter fullscreen mode Exit fullscreen mode

This will render the Modal component inside portal-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 :)


Discussion (0)