Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs which one is better form onChange or input onChange?

Tags:

reactjs

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.

like image 274
Hayk Aghabekyan Avatar asked Jan 04 '18 18:01

Hayk Aghabekyan


People also ask

What is onchange event in react?

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.

How does handlechange work 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.

What is the use of onchange in JavaScript?

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.

Should onchange be lowercase or uppercase in react?

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.


1 Answers

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.

like image 154
Luka Žitnik Avatar answered Oct 12 '22 23:10

Luka Žitnik