Lesson 9
22 min
Controlled inputs, submitting with onSubmit and handling several fields with a single state.
Definition
A controlled component is a form field (input,textarea,select...) whose displayed value is entirely controlled by a React component'sstate. The field does not have its own memory: it displays what the state contains, and every change made by the user triggers an update to that state. The state is therefore the form's single source of truth.
Lesson Objectives
value and onChange.In a traditional HTML form, the browser remembers what the user types. With React, we generally prefer the component's stateto hold that value. The field is then called controlled: its value comes from state, and every keystroke updates that state.
This may seem more complicated at first, but the benefits are significant. Since the value is stored in state, you can read it at any time, validate it while the user types, transform it (for example, convert everything to uppercase), display it elsewhere on the page, or clear the field after submission. The form becomes a simple function of your state, just like the rest of your interface.
Without a controlled field, the browser and React do not share the same information: the field contains text that your component does not know about. To retrieve that value, you would need to read it from the DOM at the last moment. With a controlled field, there is only one version of the data, stored in state, and the field always reflects it accurately.
Here is the simplest possible example. The component stores the entered text in a state variable namedname. The field displays this state usingvalueand updates it usingonChange.
import { useState } from "react";
function NameField() {
const [name, setName] = useState("");
return (
<div>
<label htmlFor="name">Your name</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Hello {name || "stranger"}!</p>
</div>
);
}
export default NameField;value: connects the field to state.onChange: updates state after every keystroke.
When the user presses a key, here is what happens:
onChangeevent is triggered by the field.e.target.value.setNamewith that value.This entire cycle happens almost instantly. That is why the field appears to behave normally, even though React is actually deciding what is displayed.
Warning: value Without onChange
If you write valuewithout onChange, the field becomes read-only: the state never changes, so the field always displays the same value and the user can no longer type. React also displays a warning in the console.
Since the value passes through state, you can modify it before storing it. For example, here is a field that automatically converts input to uppercase and counts the characters:
import { useState } from "react";
function CodeField() {
const [code, setCode] = useState("");
function handleChange(e) {
setCode(e.target.value.toUpperCase());
}
return (
<div>
<label htmlFor="code">Promo code</label>
<input id="code" value={code} onChange={handleChange} maxLength={10} />
<p>{code.length} / 10 characters</p>
</div>
);
}There is an alternative to controlled fields: let the browser manage the value and read it only when the form is submitted. This is called an uncontrolled field. You can provide an initial value using defaultValue, but React does not track what the user types.
function FreeField() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.target);
console.log("First name:", data.get("firstName"));
}
return (
<form onSubmit={handleSubmit}>
<input name="firstName" defaultValue="Aina" />
<button type="submit">Submit</button>
</form>
);
}In this course, we mainly use controlled fields because they fit naturally into the way React works. Just remember one rule: never usevalueanddefaultValueon the same field. You must choose one or the other.
These two elements are controlled like text fields, but their original HTML syntax is different, and React has simplified it. In HTML, the content of atextareais written between its tags, and the selected option of aselectuses theselectedattribute. In React, both simply usevalue.
import { useState } from "react";
function Review() {
const [comment, setComment] = useState("");
const [rating, setRating] = useState("5");
return (
<form>
<label htmlFor="rating">Rating</label>
<select
id="rating"
value={rating}
onChange={(e) => setRating(e.target.value)}
>
<option value="5">5 - Excellent</option>
<option value="4">4 - Good</option>
<option value="3">3 - Average</option>
</select>
<label htmlFor="comment">Comment</label>
<textarea
id="comment"
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
/>
<p>Rating: {rating} / 5, {comment.length} character(s)</p>
</form>
);
}Notice that the value of aselectis always a string, even when the options look like numbers: the ratingstate contains"5"rather than5. If you need to perform calculations, convert it usingNumber(rating). The same applies to an input withtype="number".
Since you decide what enters the state, you can reject certain characters. Here is a phone number field that only keeps digits: any letter typed is simply ignored.
import { useState } from "react";
function PhoneField() {
const [phone, setPhone] = useState("");
function handleChange(e) {
// Remove anything that is not a digit
const digits = e.target.value.replace(/[^0-9]/g, "");
setPhone(digits);
}
return (
<div>
<label htmlFor="phone">Phone</label>
<input id="phone" value={phone} onChange={handleChange} maxLength={10} />
</div>
);
}The expression/[^0-9]/gmeans "any character that is not a digit", andreplacereplaces those characters with an empty string. This type of filtering can be implemented cleanly with a controlled field: the field always displays what is stored in state, so rejected characters never appear on the screen.
With onSubmiton the formelement, you handle submission yourself. Remember to calle.preventDefault()to prevent the page from reloading.
By default, an HTML form reloads the page when submitted, which would cause your application to lose its state. By callingpreventDefault, you cancel this behavior and stay in control: you can validate the data, send it to a server, and then display a confirmation message.
import { useState } from "react";
function Contact() {
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [sent, setSent] = useState(false);
function handleSubmit(e) {
e.preventDefault();
console.log("Sent:", { email, message });
setSent(true);
setEmail("");
setMessage("");
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
placeholder="Your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<textarea
placeholder="Your message"
value={message}
onChange={(e) => setMessage(e.target.value)}
required
/>
<button type="submit">Send</button>
{sent && <p>Thank you, your message has been sent!</p>}
</form>
);
}
export default Contact;Notice that the fields are cleared after submission simply by resetting their states to empty strings. This is one of the major benefits of controlled fields: no DOM manipulation is necessary.
HTML attributes such asrequiredare useful, but we often want more precise rules and custom messages. We can store an error message in state and display it conditionally using conditional rendering:
import { useState } from "react";
function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
function handleSubmit(e) {
e.preventDefault();
if (!email.includes("@")) {
setError("The email must contain an @ symbol.");
return;
}
if (password.length < 6) {
setError("The password must contain at least 6 characters.");
return;
}
setError("");
console.log("Login successful");
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Log in</button>
{error && <p>{error}</p>}
</form>
);
}With a single error message, you can only report one problem at a time. To guide the user more precisely, we store an errors object: one key per field, with no error value when the field is valid.
import { useState } from "react";
function Account() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errors, setErrors] = useState({});
function validate() {
const newErrors = {};
if (!email.includes("@")) {
newErrors.email = "The email must contain an @ symbol.";
}
if (password.length < 6) {
newErrors.password = "At least 6 characters are required.";
}
return newErrors;
}
function handleSubmit(e) {
e.preventDefault();
const result = validate();
setErrors(result);
if (Object.keys(result).length === 0) {
console.log("Valid form");
}
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
{errors.email && <p>{errors.email}</p>}
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{errors.password && <p>{errors.password}</p>}
<button type="submit">Create account</button>
</form>
);
}Thevalidatefunction builds an object containing only the errors found. If this object is empty, everything is valid. We check this usingObject.keys(result).length === 0. Separating validation from rendering makes the code easier to read, and you can add a new rule without changing the JSX.
Since field values are stored in state, you can calculate whether the form is ready during each render and disable the submit button otherwise. There is no need for additional state: it is simply a calculated constant.
function CommentForm() {
const [author, setAuthor] = useState("");
const [text, setText] = useState("");
const ready = author.trim() !== "" && text.trim().length >= 10;
return (
<form onSubmit={(e) => e.preventDefault()}>
<input value={author} onChange={(e) => setAuthor(e.target.value)} />
<textarea value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit" disabled={!ready}>
Publish
</button>
{!ready && <p>Write at least 10 characters and enter your name.</p>}
</form>
);
}Live validation can display an error as soon as the first letter is typed, which can be frustrating because the user has not finished entering the value yet. TheonBlurevent, triggered when a field loses focus, lets you wait until that moment.
function EmailField() {
const [email, setEmail] = useState("");
const [touched, setTouched] = useState(false);
const invalid = touched && !email.includes("@");
return (
<div>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={() => setTouched(true)}
/>
{invalid && <p>Invalid email address.</p>}
</div>
);
}Thetouchedstate becomestruewhen the user leaves the field for the first time. Before that, no error is displayed; afterward, the error updates live as the user types.
When a form contains many fields, you can group their values intoa single object and use each field'snameattribute to identify which one has changed:
Writing a separate useStateand function for every field quickly becomes repetitive. With one object and onehandleChangefunction, the code stays concise regardless of the number of fields. The brackets aroundname(computed property syntax) allow you to update the correct object key, while the spread operator (three dots) copies the other values so nothing is lost.
import { useState } from "react";
function Registration() {
const [form, setForm] = useState({
firstName: "",
city: "",
newsletter: false,
});
function handleChange(e) {
const { name, value, type, checked } = e.target;
setForm({
...form,
[name]: type === "checkbox" ? checked : value,
});
}
return (
<form>
<input name="firstName" value={form.firstName} onChange={handleChange} />
<select name="city" value={form.city} onChange={handleChange}>
<option value="">Choose a city</option>
<option value="Antananarivo">Antananarivo</option>
<option value="Toamasina">Toamasina</option>
<option value="Mahajanga">Mahajanga</option>
</select>
<label>
<input
type="checkbox"
name="newsletter"
checked={form.newsletter}
onChange={handleChange}
/>
Receive the newsletter
</label>
</form>
);
}
Good to Know
For a checkbox, connect state to checked(not value). Also remember to connect eachlabelto its field usinghtmlFor: this improves accessibility.
Not all fields are controlled in exactly the same way. Here is a summary of the main cases:
valueand onChange.selectelement receivesvalue, rather than an attribute on each option.checkedand reade.target.checked.value, and checkedcompares the state with that value.import { useState } from "react";
function LevelSelection() {
const [level, setLevel] = useState("beginner");
return (
<form>
<label>
<input
type="radio"
name="level"
value="beginner"
checked={level === "beginner"}
onChange={(e) => setLevel(e.target.value)}
/>
Beginner
</label>
<label>
<input
type="radio"
name="level"
value="advanced"
checked={level === "advanced"}
onChange={(e) => setLevel(e.target.value)}
/>
Advanced
</label>
<p>Selected level: {level}</p>
</form>
);
}Let's bring together the concepts from this lesson: a single state object, different types of fields, validation on submission, a confirmation message, and resetting the form. First, read the entire code, then review each part.
import { useState } from "react";
const INITIAL_VALUES = {
firstName: "",
email: "",
level: "beginner",
termsAccepted: false,
};
function CompleteRegistration() {
const [form, setForm] = useState(INITIAL_VALUES);
const [errors, setErrors] = useState({});
const [confirmation, setConfirmation] = useState("");
function handleChange(e) {
const { name, value, type, checked } = e.target;
setForm({
...form,
[name]: type === "checkbox" ? checked : value,
});
}
function validate() {
const newErrors = {};
if (form.firstName.trim() === "") {
newErrors.firstName = "First name is required.";
}
if (!form.email.includes("@")) {
newErrors.email = "The email is invalid.";
}
if (!form.termsAccepted) {
newErrors.termsAccepted = "You must accept the terms.";
}
return newErrors;
}
function handleSubmit(e) {
e.preventDefault();
const result = validate();
setErrors(result);
if (Object.keys(result).length > 0) {
setConfirmation("");
return;
}
setConfirmation("Welcome " + form.firstName + "!");
setForm(INITIAL_VALUES);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="firstName">First name</label>
<input
id="firstName"
name="firstName"
value={form.firstName}
onChange={handleChange}
/>
{errors.firstName && <p>{errors.firstName}</p>}
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
value={form.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
<label htmlFor="level">Level</label>
<select
id="level"
name="level"
value={form.level}
onChange={handleChange}
>
<option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option>
</select>
<label>
<input
type="checkbox"
name="termsAccepted"
checked={form.termsAccepted}
onChange={handleChange}
/>
I accept the terms
</label>
{errors.termsAccepted && <p>{errors.termsAccepted}</p>}
<button type="submit">Register</button>
{confirmation && <p>{confirmation}</p>}
</form>
);
}
export default CompleteRegistration;name, it works for all fields, including the checkbox and dropdown list.validatefunction returns errors, andhandleSubmitdecides what happens next.A well-built form should be usable by everyone, including people who navigate with a keyboard or a screen reader. React does not handle everything for you, but a few simple habits can make a big difference.
htmlForandid. Clicking the label then places the cursor in the field.buttonwithtype="submit"allows form submission using the Enter key without additional code.<label htmlFor="email">Email address</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={error !== ""}
aria-describedby="email-error"
/>
{error && <p id="email-error">{error}</p>}Thearia-invalidattribute tells screen readers that the value is incorrect, whilearia-describedbyconnects the field to its error message, which can be read along with the field. These attributes keep their hyphenated syntax in JSX.
checked.form.firstName = ....name, your function does not know which key to update.Number(...)before performing calculations.type="button"for an action that should not submit the form.value(orchecked) andonChange.onSubmitande.preventDefault().nameattribute help avoid repetition.Exercise
Go Further
passwordandtext.import { useState } from "react";
function LoginExercise() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
function handleSubmit(e) {
e.preventDefault();
if (email.trim() === "" || password === "") {
setError("All fields are required.");
return;
}
setError("");
console.log("Logging in:", email);
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Log in</button>
{error && <p>{error}</p>}
</form>
);
}const [visible, setVisible] = useState(false);
// Inside the JSX
<input
type={visible ? "text" : "password"}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<label>
<input
type="checkbox"
checked={visible}
onChange={(e) => setVisible(e.target.checked)}
/>
Show password
</label>value but without onChange remains editable.e.target.checked.select is always a number when the options contain numbers.value and defaultValue together on the same field.Answers: False (it becomes read-only); True; False (it is still a string); False (you must choose one or the other).
[name] syntax that uses a variable as a property key.