Null event properties in a React callback
When you use setState
with the new (in React 0.13) callback argument, all the Event
object properties are null inside the callback. How can you update this.state
based on the value of the event target?
handleEvent(event) {
/* Fails! event.target is null */
setState(function() { return {text: event.target.value}; });
}
<input onChange={this.handleEvent}/>
The easiest workaround is to extract the information you need from the event outside the callback:
handleEvent(event) {
var text = event.target.value;
setState(function() { return {text: text}; });
}
event.target
is null inside the callback because React recycles events objects for performance reasons: React passes the same Event
object for multiple event handler calls, resetting the object properties each time. So by the time React executes the setState
callback, the Event
object has already lost its previous properties.
If for some reason you need the full event inside the callback, you can call event.persist()
as suggested in the Github issue.