lante
lante

Reputation: 7336

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.

Upvotes: 2

Views: 842

Answers (2)

finalfreq
finalfreq

Reputation: 6980

React does a garbage handling of sorts with events, so it will actually remove that event before the callback has taken place.

You can do e.persist() and it will work just fine, that makes sure the event hangs around and doesn't get wiped away.

Upvotes: 1

aviraldg
aviraldg

Reputation: 9154

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

Upvotes: 4

Related Questions