Working with forms and inputs in React
Form-associated elements, such as <input>
and <textarea>
, usually maintain their own internal state and update it according to the user input. In React, when the input of a form-associated element is managed using the React state, it's called a controlled component.
By default, in React, if the value
property of an input is not set, then the input internal state can be mutated by the user input. However, if the value
property is set, then the input is read-only and it expects React to manage the user input by using the onChange
React event and manage the input's state using the React state to update it if necessary. For example, this input
React element will be rendered as read-only:
<input type="text" value="Ms.Huang Jx" />
However, because React expects to find an onChange
event handler, the previous code will output a warning message on the console. To fix this, we can provide to the onChange
property a callback function to handle...