Site icon Tutorial

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.

If you find that you need the underlying browser event for some reason, simply use the nativeEvent attribute to get it. Every SyntheticEvent object has the following attributes:

As of v0.14, returning false from an event handler will no longer stop event propagation. Instead, e.stopPropagation() or e.preventDefault() should be triggered manually, as appropriate.

Event Pooling

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

function onClick(event) {

console.log(event); // => nullified object.

console.log(event.type); // => “click”

const eventType = event.type; // => “click”

setTimeout(function() {

console.log(event.type); // => null

console.log(eventType); // => “click”

}, 0);

// Won’t work. this.state.clickEvent will only contain null values.

this.setState({clickEvent: event});

// You can still export event properties.

this.setState({eventType: event.type});

}

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

 

Exit mobile version