Reputation: 3000
In the following example, the onChange
event fires each time the user type in a letter (like the onkeydown
event) is this the normal behavior?
import React from 'react';
export default class Form extends React.Component {
state = { name: '' };
_handleNameChanges = ({ target }) => {
this.setState({ name: target.value });
};
render() {
return (
<form>
<input
type="text"
name="name"
placeholder="John Doe"
onChange={this._handleNameChanges}
required
/>
</form>
);
}
}
Upvotes: 6
Views: 7505
Reputation: 21317
Yes, this is the normal behavior, what is happening is that as soon as the keyboard key is pressed, onKeyDown
is triggered before the character is typed into the form field. onChange
will only be fired if a combination of onkeydown
and onkeyup
happens. By stopping the propagation of either you will be able to not fire onChange
<input
onKeyDown={e => {e.stopPropagation(); e.preventDefault()}}
onChange={e => console('never fires')}
/>
Upvotes: 5
Reputation: 917
As mentioned above, React maps onChange
to onInput
(see here). Nonetheless, the solution is to use onBlur
instead.
Upvotes: 2
Reputation: 5650
Yes, you can see more in the React docs
The onChange event behaves as you would expect it to: whenever a form field is changed, this event is fired. We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.
Along with a few examples: https://reactjs.org/docs/forms.html
Upvotes: 4