šŸ“• Build AI Agents using LangGraph.js is now out!

React – render element outside component

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:
![ React Portals popup render element outside component](

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 and therefore it is overlapped by the .main-content where z-index: 2.

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:
React Portals popup render element outside component

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

Your email address will not be published. Required fields are marked *