facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
228.91k stars 46.84k forks source link

Bug: Events in shadow dom get duplicated when bubbling #24136

Open WorldSEnder opened 2 years ago

WorldSEnder commented 2 years ago

Events dispatching from inside a shadow-root will be handled multiple times while bubbling up the virtual DOM tree. I suspect this is because of event retargeting when crossing the boundary of the shadow dom.

React version: 17.0+, including 18-rc2

Steps To Reproduce

Click on the button in the code example below:

https://codesandbox.io/s/react-shadow-dom-event-doubling-msgnj1

The current behavior

onDivClicked is called twice per click on the button.

The expected behavior

onDivClicked should only be called once per handled click.

eps1lon commented 2 years ago

Thanks for the repro!

One native event is targetted at the shadow root child that bubbles to the shadow root. And another is targetted at the shadow root itself and bubbles from there (https://codesandbox.io/s/react-shadow-dom-event-doubling-msgnj1).

Since the shadow root is a Portal, React will bubble up a synthetic event from there even though it shouldn't because the browser is redirecting the native event with a different target.

So in this specific case React Portals really should stop propagation of events targetted at shadow root children because the browser will dispatch a new event with the shadow root itself as a target

vjee commented 1 year ago

I ran into the same problem and before discovering this issue made a similar repro. I'll leave it here just in case. https://codesandbox.io/s/blissful-mclaren-nci1dr

At the moment, stopping propagation in the event handler seems to be a good workaround.