Forms in React
💻 ReactBuild controlled forms, validate input and handle submission.
Forms are where users do real work. React keeps every field in state so you can validate before sending anything.
- Build a controlled form.
- Validate fields.
- Reset after submit.
One State Object
For a form with several fields, one object is easier to manage than many separate state values.
import { useState } from "react";
function Signup() {
const [form, setForm] = useState({ name: "", email: "" });
function handleChange(event) {
const { name, value } = event.target;
setForm(current => ({ ...current, [name]: value }));
}
return (
<form>
<input name="name" value={form.name} />
<input name="email" value={form.email} />
</form>
);
}Validation
Validate on submit for the first version. Show field errors next to the field and keep the values so the user does not retype everything.
function validate(form) {
const errors = {};
if (form.name.trim().length < 2) errors.name = "Enter at least 2 characters.";
if (!form.email.includes("@")) errors.email = "Enter a valid email.";
return errors;
}Submit
Prevent the default page reload, validate, then send the data. Disable the button while the request is running to prevent double submits.
Practice
- Add a password field with a minimum length rule.
- Show field errors under each input.
- Reset the form after a successful submit.
Hands-on exercise
Build a contact form with name, email and message.
1. Keep all values in one state object.
2. Validate on submit.
3. Show errors under the fields.
4. Clear the form on success.
Recap
Controlled inputs keep form state in React. Validate on submit, show helpful errors and reset deliberately.
Example
import { useState } from "react";
function Signup() {
const [form, setForm] = useState({ name: "", email: "" });
function handleChange(event) {
const { name, value } = event.target;
setForm(current => ({ ...current, [name]: value }));
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
</form>
);
}
Exercises
1. Keep all values in one state object.
2. Validate on submit.
3. Show errors under the fields.
4. Clear the form on success.
Expected Output
A validated form that clears after a successful submit.
Lesson Nav
React Course
0/9 lessons completed
- 1 Thinking in Components Tutorial
- 2 Props and Composition Tutorial
- 3 State and Events Tutorial
- 4 Lists, Keys and Conditional Rendering Tutorial
- 5 Forms in React Tutorial
- 6 Effects and Data Fetching Tutorial
- 7 Routing and Layouts Tutorial
- 8 Context and Shared State Tutorial
- 9 Project: A Student Dashboard Project