Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone an instance of react's synthetic event

With vanilla JS it is possible to clone an event instance like so:

const cloneEvent = event => new event.constructor(event.type, event);

Which can be used to forward event event from one DOM element to another. For example,

const buttonA = document.querySelector('#a');
const buttonB = document.querySelector('#a');

const clickHandler = (type, forwardTo) => event => {
  console.log(type, 'was clicked');
  if (forwardTo) forwardTo.dispatchEvent(cloneEvent(event));
};

buttonA.addEventListener('click', clickHandler('A', buttonB));
buttonA.addEventListener('click', clickHandler('B'));

When you click on A you will also see 2 loggings for both buttons.

I would like to achieve the same with React's SyntheticEvent but I am running to issues presumably because SyntheticEvent have a different way of instantiation than native events. Here's a live demo that illustrates the problem: https://jsfiddle.net/2Lhsfceu/2/ (see the dev console logs)

My current solution is to clone the native event (SyntheticEvent.nativeEvent) as follows (updated and working live demo: https://jsfiddle.net/2Lhsfceu/1/)

const cloneEvent = event => {
  const nativeEvent = event.nativeEvent || event;
  new nativeEvent.constructor(nativeEvent.type, nativeEvent);
}

I am wondering if there's a cleaner way or if this is the best we can do?

My concern is that by cloning only the native event the code base is dealing with two different types of events: the SyntheticEvent dispatched by the source event (coming from React) and the native event from forwarding.

like image 968
F Lekschas Avatar asked Dec 19 '25 08:12

F Lekschas


1 Answers

As soon as dispatching the native event on the DOM is exactly like scrolling manually, it should be fine.

My concern is that by cloning only the native event the code base is dealing with two different types of events: the SyntheticEvent dispatched by the source event (coming from React) and the native event from forwarding.

What React does is that it listens to all native events on the root (the <div id="#root"/> here, they get there through bubbling), then each time it receives one it creates an equivalent SyntheticEvent that gets passed in the React code.

So if you fire native events manually, React will create their SyntheticEvent equivalent as usual, and it should be fine.

On very rare occasions, dispatching an event manually in Javascript will have a different effect than having a real user trigger the event. See this example.

like image 149
Emmanuel Meric de Bellefon Avatar answered Dec 22 '25 00:12

Emmanuel Meric de Bellefon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!