Controlled Components in React
Learn how React state controls form input values and how to handle text inputs, multiple fields, and form updates.
1. Introduction to Controlled Components
A controlled component is a form element whose value is controlled by React state. The input receives its value through a value prop, and an event handler updates the state when the user changes the input.
Because React state stores the current value, the component can read, display, validate, and update the information entered by the user.
value and onChange.
2. How Controlled Components Work
React stores the input value in state. When the user types, the onChange handler updates that state, and React renders the input with the latest value.
3. Creating a Controlled Text Input
We can use the useState hook to store a text input's value. The onChange handler reads the latest value from the event object and updates the state.
Example
import { useState } from "react";
function NameInput() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<label htmlFor="studentName">
Student Name:
</label>
<input
id="studentName"
type="text"
value={name}
onChange={handleChange}
/>
<p>Name: {name}</p>
</div>
);
}
export default NameInput;
Expected Output
Name: Rahul
The value of the input comes from the name state. When the user types, handleChange updates the state and React displays the new name.
4. Using an Inline onChange Handler
Instead of defining a separate function, we can write an arrow function directly inside the onChange prop. This is useful for simple input updates.
Example
import { useState } from "react";
function EmailInput() {
const [email, setEmail] = useState("");
return (
<div>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) =>
setEmail(event.target.value)
}
/>
<p>Email: {email}</p>
</div>
);
}
export default EmailInput;
Expected Output
Email: student@example.com
The inline arrow function reads event.target.value and passes the entered email to setEmail.
5. Handling Multiple Controlled Inputs
A form can contain multiple controlled inputs. We can store their values in one state object and use each input's name attribute to identify which value to update.
Example
import { useState } from "react";
function RegistrationForm() {
const [formData, setFormData] = useState({
name: "",
email: ""
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
}
return (
<div>
<label htmlFor="name">Name:</label>
<input
id="name"
name="name"
value={formData.name}
onChange={handleChange}
/>
<label htmlFor="email">Email:</label>
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
/>
<p>Name: {formData.name}</p>
<p>Email: {formData.email}</p>
</div>
);
}
export default RegistrationForm;
Expected Output
Name: Rahul
Email: rahul@example.com
The name property identifies the field being updated. The spread operator keeps the other form values when the state object is updated.
6. Creating a Controlled Checkbox
For a checkbox, the checked prop represents whether the checkbox is selected. The onChange handler updates the state when the user checks or unchecks it.
Example
import { useState } from "react";
function TermsCheckbox() {
const [accepted, setAccepted] = useState(false);
return (
<div>
<label>
<input
type="checkbox"
checked={accepted}
onChange={(event) =>
setAccepted(event.target.checked)
}
/>
I accept the terms and conditions
</label>
<p>
Accepted: {accepted ? "Yes" : "No"}
</p>
</div>
);
}
export default TermsCheckbox;
Expected Output
Accepted: No
A checkbox uses checked rather than value to control whether it is selected. The event's target.checked property provides its current boolean value.
7. Creating a Controlled Select
A select element allows users to choose an option. Its value prop can be connected to state so React controls the selected option.
Example
import { useState } from "react";
function CourseSelect() {
const [course, setCourse] = useState("React");
return (
<div>
<label htmlFor="course">Choose a Course:</label>
<select
id="course"
value={course}
onChange={(event) =>
setCourse(event.target.value)
}
>
<option value="React">React</option>
<option value="Angular">Angular</option>
<option value="Python">Python</option>
</select>
<p>Selected Course: {course}</p>
</div>
);
}
export default CourseSelect;
Expected Output
Selected Course: React
The selected course is stored in state. When the user chooses a different option, the onChange handler updates the course value.
8. Common Mistakes
Mistake 1: Missing the onChange Handler
<input value={name} />
A text input with a value prop but no state-updating handler is read-only from the user's perspective.
Correct Code
<input
value={name}
onChange={(event) =>
setName(event.target.value)
}
/>
Mistake 2: Using value for Checkbox Selection
<input
type="checkbox"
value={accepted}
/>
The value prop does not control whether a checkbox is selected. Use the checked prop instead.
Correct Code
<input
type="checkbox"
checked={accepted}
onChange={(event) =>
setAccepted(event.target.checked)
}
/>
Mistake 3: Losing Other State Properties
setFormData({
[name]: value
});
This replaces the state object and removes properties that were not included in the new object.
Correct Code
setFormData((previousData) => ({
...previousData,
[name]: value
}));
9. Practice Tasks
Complete these tasks to practise controlled components.
Summary
Controlled components are form elements whose values are managed by React state. Text inputs and select elements commonly use value with onChange, while checkboxes use checked with onChange. State can store one input value or an object containing multiple form values. Updating state through event handlers keeps the displayed fields synchronized with React and provides a reliable foundation for form validation and submission.