Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to check if any object is a SyntheticEvent?

Tags:

reactjs

What is the best way to check if a given object of any kind is a SyntheticEvent?

Currently, I'm peering into the internals:

if (obj.nativeEvent ) {
    // 100% sure...with this version of React
}

What is a more idiomatic (or at least future-proof) way of doing this?

like image 225
Ashley Coolman Avatar asked May 17 '17 16:05

Ashley Coolman


People also ask

What is SyntheticEvent?

Your event handlers will be passed instances of SyntheticEvent , a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault() , except the events work identically across all browsers.

What is onClickCapture?

React onClickCapture is an event handler that gets triggered whenever we click on an element. like onclick, but the difference is that onClickCapture acts in the capture phase whereas onClick acts in the bubbling phase i.e. phases of an event.

How do you use stopPropagation React?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.


1 Answers

You can use such check: if (!(event instanceof Event)).

event (which is SyntheticEvent) will give false in this case and event.nativeEvent will give true.

like image 126
lunochkin Avatar answered Oct 13 '22 19:10

lunochkin