user9623401
user9623401

Reputation:

quirks of input element in React

I'm new to React, sorry if my questions are trivial.

In React, if I write:

<input value="" />

then it will be an read-only field, and React forces me to add an onChange handler as:

<input value={this.state.greeting} onChange={this.handleChange} />

where handleChange() update component's state.greeting, therefore value gets updated too

Below are my questions:

Q1-why <input value="" /> is not read-only in plain html but read-only in React? How does React make it read-only

Q2-I found that if I write the code as below it also works, the input is not read-only

<input onChange={this.handleChange} />

and isn't that this approach better and more concise? because the internal value will get updated automatically in the browser, therefore we don't need to include an value attribute to read the data back from the state, which is unnecessary in most of times, so why I always see code like:

<input value={this.state.greeting} onChange={this.handleChange} />

Additional info:

some says it is controlled form elements that needs to have value attribute, but why we need to have a value attribute to read from the state? and when we type sth into the input, the onChange handler already updates the state, so it is still controlled.

Upvotes: 1

Views: 84

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76444

To know how React makes your tags readonly, you will need to study the source-code that runs at your end and/or view the generated HTML. If still unsure about it, then you might want to send your first question to the authors of the tool.

The state is not on the server, unless you are polling or doing something of the like. It's in your browser as well. The value property specifies the initial value of your HTML element, that is, before you do anything your tag will have a value. In your case, your tag is controlled by React, but you need to initialize it. Benefits:

  • you will have the initial value
  • you will have a more readable code
  • your code will be written in the React-way, so you will not need to worry of unpleasant surprises

Upvotes: 0

Related Questions