React.js / React Forms and Validation
Creating Controlled and Uncontrolled Components
In this tutorial, we'll explore how to create controlled and uncontrolled components in React. You'll learn the differences between the two, how they work, and when to use each ty…
Section overview
5 resourcesExplores handling forms, input, and validation in React applications.
1. Introduction
In this tutorial, we aim to understand how to create Controlled and Uncontrolled Components in React. We will delve deep into their differences, understand how they operate, and learn when to use each type.
By the end of this tutorial, you should be able to:
- Understand what Controlled and Uncontrolled Components are.
- Create Controlled and Uncontrolled Components.
- Understand when to use each type.
Prerequisites
- Basic understanding of JavaScript.
- Familiarity with React and its syntax.
2. Step-by-Step Guide
Controlled Components
In React, a controlled component is a component that takes its current value through props and notifies changes through callbacks like onChange. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component.
Example of a Controlled Component:
class ControlledComponent 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>
);
}
}
Uncontrolled Components
Unlike controlled components, uncontrolled components store their own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
Example of an Uncontrolled Component:
class UncontrolledComponent extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
3. Code Examples
Controlled Component Example
//This is a Controlled Component
class ControlledComponent extends React.Component {
state = {
text: ''
}
//Handle change function is used to update the state
handleChange = (event) => {
this.setState({ text: event.target.value });
}
render() {
return (
<input
type="text"
value={this.state.text}
onChange={this.handleChange}
/>
);
}
}
In the above example, the input field's value is controlled by the state within the component.
Uncontrolled Component Example
//This is an Uncontrolled Component
class UncontrolledComponent extends React.Component {
input = React.createRef();
handleClick = () => {
alert(this.input.current.value);
}
render() {
return (
<div>
<input
type="text"
ref={this.input}
/>
<button onClick={this.handleClick}>Alert the Value!</button>
</div>
);
}
}
In this example, we use ref to "get" the value from the input field.
4. Summary
In this tutorial, we've covered the differences between Controlled and Uncontrolled Components in React. We've learned how to create each type and when to use them. While Controlled Components have more control and predictability, Uncontrolled Components allow more flexibility and are closer to traditional HTML.
To further enhance your skills, you may want to learn more about forms and handling events in React.
5. Practice Exercises
-
Create a Controlled Component which takes user input and displays it in real time.
-
Create an Uncontrolled Component which takes user input and displays it when a button is clicked.
Solution
- Controlled Component
class ControlledComponent extends React.Component {
state = {
text: ''
}
handleChange = (event) => {
this.setState({ text: event.target.value });
}
render() {
return (
<div>
<input
type="text"
value={this.state.text}
onChange={this.handleChange}
/>
<p>{this.state.text}</p>
</div>
);
}
}
- Uncontrolled Component
class UncontrolledComponent extends React.Component {
input = React.createRef();
handleClick = () => {
this.setState({ text: this.input.current.value });
}
render() {
return (
<div>
<input
type="text"
ref={this.input}
/>
<button onClick={this.handleClick}>Display Value</button>
<p>{this.state.text}</p>
</div>
);
}
}
In these exercises, we put into practice what we learned by creating Controlled and Uncontrolled Components. You can enhance your skills further by trying to convert a Controlled Component into an Uncontrolled one and vice versa.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article