../courses.php
React
REACT106
90
Forms
Use controlled inputs to collect information from users.
How does React handle form input?
React often handles forms with controlled inputs. The input value comes from state, and onChange updates that state as the user types.
Forms are where users talk back to the interface.
A React form can collect names, emails, search text, filters, settings, comments, and login details.
In a controlled input, React state is the source of truth.
The field displays the state value, and typing updates the state value.
This makes validation, previews, clearing, and submitting easier to manage.
A controlled React form
import { useState } from "react";
function ContactForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
function handleSubmit(event) {
event.preventDefault();
setMessage(`Thank you, ${name}. We will contact ${email}.`);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<button type="submit">Send</button>
<p>{message}</p>
</form>
);
}
Each field has a state value.
value={name} makes the input display React state.
onChange updates state when the user types.
event.preventDefault() stops the browser from reloading the page on submit.
The submit handler creates a message from the current form state.
Control
React can always know the current field value.
Validation
State makes it easier to check fields before submitting.
Live preview
The screen can update while the user types.
Form flow
React can handle typing, errors, submit messages, and clearing in one flow.
Uncontrolled and hard to track
<input id="name" />
<button>Submit</button>
Controlled input
<input
value={name}
onChange={(event) => setName(event.target.value)}
/>
Ask ChatGPT: "Which inputs in this React form are controlled, and what state value controls each one?" Then trace every field.
Create state for name and email.
Connect each input value to state.
Add onChange handlers.
Add onSubmit to the form.
Use preventDefault() and show a confirmation message.
Forgetting event.preventDefault() on submit.
Using state for some fields but not others without a reason.
Forgetting onChange on a controlled input.
Reading form values from the DOM instead of React state.
Putting all form logic in one messy handler when it needs clearer structure.
Build controlled React forms with state, input handlers, submit handlers, and clear user feedback.
Login - Jit4All
Login
Welcome back to Jit4All