A form gathers several fields and submits them together. This one plans a study session. Try saving with an empty title, then with 2 minutes, then with valid values.
npm install and npm run dev. onSubmit and preventDefault
The handler goes on the <form>, not on the button:
<form onSubmit={handleSubmit}>
...
<button type="submit">Save</button>
</form>That way pressing Enter in a field submits too, as users expect.
By default, a browser submits a form by loading a new page, which would throw
away all your state. The first line of handleSubmit stops that:
event.preventDefault();Delete that line, fill in a title and press Save. The Saved line never stays: the browser submits the form and starts the app again. Put the line back.
Every field's value is a string
Even <input type="number"> gives you a string in event.target.value. The
minutes state stays a string while the user types, which allows a field that's
briefly empty. It's turned into a number only when the form is submitted:
const amount = Number(minutes);Number("") is 0, and Number("abc") is NaN. Number.isInteger
rejects NaN and 2.5, but accepts 0. This form also requires
amount >= 5 && amount <= 180, so 0 is rejected by the range check.
Check both the converted number and the allowed range.
Selects and checkboxes
A <select> is controlled the same way as a text field: value={level} and
onChange={(e) => setLevel(e.target.value)}. The <option> whose value
matches is selected:
<select value={level} onChange={(e) => setLevel(e.target.value)}>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</select>A checkbox uses checked instead of value, and its new state is
e.target.checked, which is true or false:
<input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />Validation
handleSubmit checks each rule in turn. The first failure sets an error
message and returns before saving. Everything passing clears the error,
saves, and empties the title for the next session:
function handleSubmit(event) {
event.preventDefault();
const amount = Number(minutes);
if (title.trim() === "") {
setError("Give the session a title.");
return;
}
if (!Number.isInteger(amount) || amount < 5 || amount > 180) {
setError("Minutes must be a whole number from 5 to 180.");
return;
}
setError("");
setSaved({ title: title.trim(), minutes: amount, level });
setTitle("");
}Errors are state too, so they appear and disappear through ordinary rendering:
{error && <p className="error">{error}</p>}.
Showing every error at once
Stopping at the first failure is simple, but it's annoying to use. Leave both fields wrong and press Save: you're told about the title. Fix it, press Save again, and only now do you hear about the minutes.
To show every problem at once, check all the rules first and collect the messages in an object, one key per field. Then decide whether to save:
const errors = {};
if (title.trim() === "") {
errors.title = "Give the session a title.";
}
if (!Number.isInteger(amount) || amount < 5 || amount > 180) {
errors.minutes = "Minutes must be a whole number from 5 to 180.";
}
setErrors(errors);
if (Object.keys(errors).length > 0) {
return;
}Object.keys(errors) is an array of the object's key names, such as
["title", "minutes"], so a length of 0 means every rule passed. The state
starts as an empty object, useState({}), and each field shows its own
message underneath it:
{errors.title && <p className="error">{errors.title}</p>}Use the first-failure version when one message is enough, and the collecting version when a form has several fields the user fills in together. The Day 5 checkpoint needs the second.
Your turn
A reminder checkbox
Add a checkbox, Remind me, that starts unticked. Include it in the saved session, and show with a reminder at the end of the saved line when it was ticked.
npm install and npm run dev. Hint 1: the idea
A checkbox is a controlled input like the others, but it is either on or off. So its state starts as a true/false value, and it reads and writes a different property from a text field. To show it after saving, the saved object has to remember it too.
Hint 2: a first step
Add the state and the checkbox first, using the pattern from Selects and
checkboxes above. Tick and untick it: the box follows your clicks, so the
state is wired up. Next, save a session and ask what setSaved receives. Is
the checkbox's value in there?
Show one solution
const [remind, setRemind] = useState(false);<label>
<input type="checkbox" checked={remind} onChange={(e) => setRemind(e.target.checked)} />{" "}
Remind me
</label>setSaved({ title: title.trim(), minutes: amount, level, remind });<p>
Saved: {saved.title}, {saved.minutes} minutes, {saved.level}
{saved.remind && ", with a reminder"}.
</p>Completion is saved in this browser only. It does not measure mastery.