A controlled component in React is a form element whose value is managed by React state. Instead of the browser managing input values, React becomes the single source of truth.
This gives predictable behavior and enables features like validation, formatting, and real-time UI updates.
value attribute must always reference state.onChange handler must update state.
// Controlled input using React state
import React, { useState } from "react";
function ControlledInput() {
const [name, setName] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
return (
<div>
<h4>Controlled Input Example</h4>
<input type="text" value={name} onChange={handleChange} placeholder="Enter your name" />
<p>Hello, {name || "Guest"}!</p>
</div>
);
}
// Handling multiple inputs using a single state object
function ControlledForm() {
const [formData, setFormData] = React.useState({
username: "",
email: ""
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`User: ${formData.username}\nEmail: ${formData.email}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" value={formData.username} onChange={handleChange} />
<input type="email" name="email" value={formData.email} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}
// Controlled dropdown and textarea
function FeedbackForm() {
const [feedback, setFeedback] = React.useState({
rating: "Good",
comment: ""
});
const handleChange = (e) => {
const { name, value } = e.target;
setFeedback({ ...feedback, [name]: value });
};
return (
<form>
<select name="rating" value={feedback.rating} onChange={handleChange}>
<option>Excellent</option>
<option>Good</option>
<option>Average</option>
<option>Poor</option>
</select>
<textarea name="comment" value={feedback.comment} onChange={handleChange}></textarea>
<p>Your feedback: {feedback.comment || "No comment yet"}</p>
</form>
);
}
This interactive demo simulates how a controlled component works by keeping the input value and UI display perfectly synchronized.
Hello Guest (Role: Student)
This guarantees consistent two-way data flow and eliminates unsynced input issues.
onChange or onSubmit.useForm().Goal: Build confidence managing form inputs using React state.