We want to use React Portals so that a component is rendered in some other place it was supposed to be rendered. Imagine something like a cut-paste.
So let's say we have this markup:
<body>
<div id="root"></div>
<div id="popup-container"></div>
</body>
The id="root"
serves as the placeholder for the following app component:
export default function App() {
return(<>
<Popup>
Popup content here
</Popup>
<!-- more page content here -->
</>
}
We want to move the just <Popup>
component from within id="root"
to id="popup-container"
.
Why would we want to do this?
Take a look at this codepen.
It just has a popup component that renders its children's elements when a button is clicked.
However, when we open the popup we will see the below problem:
This happens because of how z-index works. It creates stacking contexts, so even if the .popup
has z-index: 1000
it cannot escape the context of its parent #root
where z-index: 1
.
Here is where the React Portals come into play. Even if the <Popup>
component is defined in <App>
, and the <App>
component is rendered in the <div id="root">
we can cut and paste the popup so that is rendered in another parent.
In this case, we will move the popup to <div id="popup-container">
so it can escape the stacking context with z-index: 1
.
So, we will first need to import createPortal()
:
import { createPortal } from "react-dom"
And next move the popup to a given new parent:
const Popup = ({ open, children, onClose }) => {
return open && createPortal(
<>
<!-- popup content here -->
</>,
document.getElementById('popup-container')
)
}
And that's it! This will solve our z-index problems:
You can checkout here the full codepen with the working React Portals example.
You may also be interested in how React Portals handles event delegation.
š Neural networks for Javascript developers
The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!