Controlled Components
A controlled input, or controlled component, is what we will be using most of the time when we want to implement forms in React.
The controlled part comes from the fact that the parent component possesses a reference to the current value that we assign to the input element. That value can be controlled using setState
, while managing the state or the value can be passed as a prop from the parent component to its children components.
Let's take a look at the following code snippet:
handleOnNameChange = (e) => { Â Â this.setState({ name: e.target.value }); }; <input type="text" value={this.state.name} onChange={this.handleOnNameChange} />
To obtain the current value of the input element and for any other updates of that element thereafter, we use the onChange
event handler (or any similar handler that triggers when the actual DOM input gets updated). Then, on the event object itself, we get the current value using the e...