Alexander Suraphel Alexander Suraphel - 1 year ago 569
Javascript Question

Why does react make input[type="text"] fields readonly unless I supply onChange callback?

Initially I had:

<input type="text"id="requested" name="requested" ref="requested" />

which was readonly.

changing it to:

<input type="text" onChange={function() {}} id="requested" name="requested" ref="requested" />

made it accept input from keyboard. Why does this happen?

Answer Source

The example you list is not read-only. See this JSFiddle:

If you add a value={whatever} property to the input, which makes it a controlled component, then it is read-only uness you add an onChange handler that updates the value of whatever. From the React docs:

Why Controlled Components?

Using form components such as <input> in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:

<input type="text" name="title" value="Untitled" />

This renders an input initialized with the value, Untitled. When the user updates the input, the node's value property will change. However, node.getAttribute('value') will still return the value used at initialization time, Untitled.

Unlike HTML, React components must represent the state of the view at any point in time and not only at initialization time. For example, in React:

render: function() {
  return <input type="text" name="title" value="Untitled" />;

Since this method describes the view at any point in time, the value of the text input should always be Untitled.