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.
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!