šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

React Portals and Event delegation

In React Portals we have an event delegation mechanism built in that allows the event propagation to be made to the parent component even if a child component was moved via a React Portal.

So, coming back to the previous example where we build a React popup using portals.

We have the Popup component as a child of the App component.

export default function App() {
    return(<>
        <Popup>
            Popup content here
        </Popup>
    </>
}

But Popup is a child of App just from a JSX point of view! Because we have moved it using the portal.

If we inspect the real DOM we will see that the Popup is actually placed inside of #popup-container and has nothing to do with the #root element where App is placed.

React portal JSX elements vs the Real Dom

The cool stuff about the event delegation system of react portals is that the events are still captured by the JSX parents.

So, if we add a click action lister in the App component, that listener will be applicable also to the Popup component without us needing to do any extra wiring:

const App = ()=> {
  /* the below onClick() listener will also work in the Popup
even if the Popup is moved with a Portal */
  return (
    <div onClick={() => console.log('Click on APP!')}>
        <Popup></Popup>
    </div>
  )
}

Pretty cool! You can check the working codepen below. Be sure to have your console opened.

See the Pen
Untitled
by JS Craft (@js-craft)
on CodePen.

šŸ“– 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.


Leave a Reply

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