We can use React Portals to render a component outside its designated container.
For example, we can use a portal to take out a React sub-component from the standard root div. Imagine something like a cut-paste operation.
This can be very useful when working with popups.
Let's say we have this markup:
<body>
<div id="root"></div>
<div id="popup-container"></div>
<div class="main-content">Lorem Ipsum is simply ... </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 just the <Popup>
component from within id="root"
to id="popup-container"
.
Why would we want to do this?
Take a look at this live example live example. Full code here.
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:

:
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 check out the working example on GitHub pages and the full code here.
You may also be interested in how React Portals handles event delegation.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.