Ashley Coolman
Ashley Coolman

Reputation: 11585

Correct way to check if any object is a SyntheticEvent?

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?

Upvotes: 17

Views: 6143

Answers (2)

lunochkin
lunochkin

Reputation: 784

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.

However, that check alone will not tell you whether the event was a "real browser event" or something generated by JS (after all, you can create and send events into the DOM using new Event(...) and then using element.dispatch(event)), so if you need to know whether you're dealing with a real browser event or not (rather than synthetic or not) you'll need to check the isTrusted event property. This property will only be true for real, browser-generated events and will report false for events generated in JS.

Upvotes: 11

gpbl
gpbl

Reputation: 4804

I check if obj.constructor.name === 'SyntheticEvent'.

Upvotes: 4

Related Questions