Controlled Components
suggest changeA controlled component is bound to a value, and its changes are handled in code with event-based callbacks.
class CustomForm extends React.Component {
constructor() {
super();
this.state = {
person: {
firstName: '',
lastName: ''
}
};
}
handleChange(event) {
let person = Object.assign({}, this.state.person);
person[event.target.name] = event.target.value;
this.setState({person});
}
render() {
return (
<form>
<input
type="text"
name="firstName"
value={this.state.person.firstName}
onChange={this.handleChange.bind(this)} />
<input
type="text"
name="lastName"
value={this.state.person.lastName}
onChange={this.handleChange.bind(this)} />
</form>
);
}
}
In this example we initialize state with an empty person object. We then bind the values of the two inputs to the individual keys of the person object. As the user types, we capture each value in the handleChange function. Since the values of the inputs are bound to state, we can rerender as the user types by calling setState(). Copy the person object before writing to it so you do not mutate state directly.
NOTE: Not calling setState() when dealing with controlled components, will cause the user to type, but not see the input because React only renders changes when it is told to do so.
It’s also important to note that the names of the inputs are same as the names of the keys in the person object. This allows us to capture the value in dictionary form as seen here.
handleChange(event) {
let person = Object.assign({}, this.state.person);
person[event.target.name] = event.target.value;
this.setState({person});
}
person[event.target.name] is the same as person.firstName or person.lastName. Which one it is depends on which input is currently being typed in. Since we don’t know where the user will be typing, matching the input name to the object key lets us capture the user input no matter which onChange runs.