React Portals and 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!

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.

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


Leave a Reply

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

Home Screencasts Best of Newsletter Search X

Neural Networks for JavaScript developers
Presale - 15$ free coupon

Hi friend! Before you go, just wanted to let you know that in March 2023 I will be launching the TensorFlow.Js by Example course.

This course will include basic concepts of AI and Neural Networks done with TensorFlowJs such as:

  • Working with datasets
  • Visualizing training
  • Deep Neural Networks in JavaScript
  • Reinforcement Learning
  • Convolutional neural networks
  • and much more ...

Also, there will be a lot of examples as:

  • Object detection
  • Natural language processing
  • Face and voice recognition
  • Gaming AI

Join now the waiting list and get a 15$ coupon off the launching price!

X