What is a controlled component in React?
Answer
A controlled component in React is a component where the value of the input element is controlled by the React component's state. This means that the value of the input element is not directly set by the user, but rather by the state of the component. This allows the component to have full control over the value of the input element, and to be able to manipulate it as needed.
For example, let's say we have a form with an input element for a user's name. In a controlled component, the value of the input element would be set by the state of the component, like so:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
In this example, the value of the input element is set to the value of the component's state, and the onChange event updates the state with the new value of the input element. This allows the component to have full control over the value of the input element, and to be able to manipulate it as needed. Overall, using controlled components in React can help to simplify the management of form data and make it easier to manipulate and validate user input.
Related React job interview questions
What are React hooks?
React JuniorWhat is uncontrolled component in React?
React JuniorHow is state different than props in React?
React JuniorWhat are props in React?
React JuniorWhat is mounted component in React?
React Junior