lante lante - 1 year ago 142
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:


And then this is my

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

}, () => {
onChange({ value: });

The issue

The thing is that on the
method, when setting the state,
contains the input element, but on the callback for the
is null (so the
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
, I can use that target on the callback. But I would like to understand why is that
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 Source

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()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download