6

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>
    );
  }
}
Ahmed Kamal
  • 2,660
  • 3
  • 21
  • 36

3 Answers3

5

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')}
/>
Dupocas
  • 20,285
  • 6
  • 38
  • 56
4

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

skovy
  • 5,430
  • 2
  • 20
  • 34
2

As mentioned above, React maps onChange to onInput (see here). Nonetheless, the solution is to use onBlur instead.

stackoverflowed
  • 686
  • 8
  • 22