There are two ways you can get input changes in your React app.
One is by using
<input type="text" onChange={this.handleChange} />
The other was is
<form onChange={this.handleChange} onSubmit={this.handleChange} />
...
</form>
When you should use first one and when the other one.
React onChange Events (With Examples) The onChange event in React detects when the value of an input element changes. Let’s dive into some common examples of how to use onChange in React.
Since handleChange runs on every keystroke to update the React state, the displayed value will update as the user types. With a controlled component, the input’s value is always driven by the React state. While this means you have to type a bit more code, you can now pass the value to other UI elements too, or reset it from other event handlers.
The onChange handler will listen for any change to the input and fire an event when the value changes. With a text input field like this, we can pass the onChange prop: The value of the prop is the handleChange function; It is an event handler.
As mentioned before, JavaScript’s native onchange syntax is written in all lowercase, however we use camel-case for our event handler names in React. Let’s expand on the previous example by declaring a new function inside of our React component for the onChange handler to pass a value to.
The reason that there are two ways is because there are more than the two ways. You can do this too:
<div onChange={this.handleChange}>
<form>
<input />
</form>
</div>
I'd argue that the first approach is better because the handler receives the event as early as possible and possibly because the binding between the input and the component state is encoded within the render function, but that depends on what the handler would look like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With