Welcome to our React JS tutorial on Controlled vs Uncontrolled Components! In this in-depth guide, we'll cover everything you need to know about these fundamental concepts.
Let's start with a brief overview:
Controlled Components:
Uncontrolled Components:
Controlled components are useful when you want to manage user input and validate it before submitting, while uncontrolled components are useful when you want to give the user more freedom and trust them to fill in the form correctly.
Let's create a simple example of a Controlled Component:
import React, { Component } from 'react';
class ControlledForm extends 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>
);
}
}
export default ControlledForm;In this example, the ControlledForm component manages the form state and updates it whenever the user types something into the input field.
Now let's create a simple example of an Uncontrolled Component:
import React, { Component } from 'react';
class UncontrolledForm extends Component {
handleSubmit(event) {
alert('A name was submitted: ' + event.target.elements.name.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name="name" />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default UncontrolledForm;In this example, the form state is managed by the browser and the value is directly provided by the user.
Controlled Components are preferred when you need to validate user input, manage state centrally, and maintain consistency across your application. Uncontrolled Components are preferred when you want to provide more freedom to the user and don't need to validate their input.
It's possible to convert an Uncontrolled Component into a Controlled Component, and vice versa, depending on your needs.
What are Controlled Components in React?
We hope you found this tutorial helpful! Stay tuned for more in-depth lessons on React JS. Happy coding! 🎉