lante lante - 1 month ago 17
React JSX Question

React event being updated onChange


Disclaimer: to quickly see the issue, please see this pen and type something there.


The implementation



I have this JSX code for my render method:

<input
value={this.state.value}
onChange={this.handleChange}
/>


And then this is my
handleChange
method:

handleChange(e) {
const { onChange } = this.props;

this.setState({
value: e.target.value,
}, () => {
onChange({ value: e.target.value });
});
}


The issue



The thing is that on the
handleChange
method, when setting the state,
e.target
contains the input element, but on the callback for the
setState
method,
e.target
is null (so the
onChange
method is not being called).

Yes, it has an obvious workaround



Of course that if I set a var to store the target before firing
setState
, I can use that target on the callback. But I would like to understand why is that
e
being updated (and the target being removed from there), if this is just an issue or its just the way that it should work. Again, this pen will show the issue.

Answer

You're running into consequences of the fact that what React passes you are actually synthetic events, that are recycled. Quoting the docs:

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.

The workaround is to store the target beforehand, or to do as the docs say, and call event.persist()

Comments