Skip to content

Checkpoint: A Keyboard-Friendly Add Form

The Course
•
20 min study

Close the earlier lessons and build this from the brief. The starter adds cards, but has no validation and no focus management, and new cards appear out of sight at the bottom of a scrolling list.

The brief

  • Validation: a blank title shows Enter a title.; minutes that aren't a whole number above 0 show Enter whole minutes above 0.. Show each error through Field's error prop, and focus the first invalid field.
  • After adding: clear the title, keep the minutes, put focus back in Title, and scroll the new card into view in the list, outlined with the selected class.
  • Escape, pressed anywhere in the form, clears both fields back to their starting values and the errors, and focuses Title.

Acceptance checks:

  • Add with an empty title: the error appears and Title has focus.
  • A valid card appears at the bottom of the list, scrolled into view and outlined, and you can type the next title straight away.
  • Typing in the form never scrolls the list.
Your workspace React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Field from "./Field.jsx"; import { manyCards } from "./manyCards.js"; export default function App() { const [cards, setCards] = useState(manyCards); const [title, setTitle] = useState(""); const [minutes, setMinutes] = useState("15"); // Make adding a card keyboard-friendly. See the brief. function handleSubmit(event) { event.preventDefault(); setCards([...cards, { id: Date.now(), title: title.trim(), column: "todo", minutes: Number(minutes) }]); setTitle(""); } return ( <main> <h1>Study Board</h1> <form onSubmit={handleSubmit} noValidate> <Field label="Title" value={title} onChange={setTitle} /> <Field label="Minutes" type="number" value={minutes} onChange={setMinutes} /> <button type="submit">Add</button> </form> <ul className="cards" style={{ maxHeight: "9rem", overflowY: "auto" }}> {cards.map((card) => ( <li key={card.id} className="card">{card.title}</li> ))} </ul> </main> ); } import { useId } from "react"; // A labelled input. useId gives each instance its own ids, so the label and // the error message point at the right input even when the field is reused. export default function Field({ ref, label, value, onChange, error, type = "text" }) { const id = useId(); const errorId = `${id}-error`; return ( <p> <label htmlFor={id}>{label}</label>{" "} <input ref={ref} id={id} type={type} value={value} onChange={(e) => onChange(e.target.value)} aria-invalid={error ? true : undefined} aria-describedby={error ? errorId : undefined} /> {error && <span id={errorId} className="error"> {error}</span>} </p> ); } export const manyCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, { id: 5, title: "Write reducer tests", column: "todo", minutes: 20 }, { id: 6, title: "Add undo", column: "doing", minutes: 25 }, { id: 7, title: "Split contexts", column: "todo", minutes: 15 }, { id: 8, title: "Use composition", column: "done", minutes: 15 }, { id: 9, title: "Focus a field", column: "todo", minutes: 10 }, { id: 10, title: "Measure renders", column: "todo", minutes: 20 }, { id: 11, title: "Try useTransition", column: "todo", minutes: 25 }, { id: 12, title: "Write a custom hook", column: "todo", minutes: 30 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: refs you need

One ref for each field, passed through Field's ref prop, and a Map of card elements filled by a ref callback on each <li>.

Hint 2: scrolling at the right moment

The new card's <li> doesn't exist until React re-renders. Store the new card's id in state, and scroll in an effect that runs when that id changes. By then the element is in the Map.

Show one solution
One solution React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useRef, useState } from "react"; import Field from "./Field.jsx"; import { manyCards } from "./manyCards.js"; export default function App() { const [cards, setCards] = useState(manyCards); const [title, setTitle] = useState(""); const [minutes, setMinutes] = useState("15"); const [errors, setErrors] = useState({}); const [lastAddedId, setLastAddedId] = useState(null); const titleRef = useRef(null); const minutesRef = useRef(null); const itemsRef = useRef(new Map()); // After a card is added and on screen, bring it into view. useEffect(() => { if (lastAddedId !== null) itemsRef.current.get(lastAddedId)?.scrollIntoView({ block: "nearest" }); }, [lastAddedId]); function clearForm() { setTitle(""); setMinutes("15"); setErrors({}); titleRef.current.focus(); } function handleSubmit(event) { event.preventDefault(); const amount = Number(minutes); const found = {}; if (title.trim() === "") found.title = "Enter a title."; if (!Number.isInteger(amount) || amount <= 0) found.minutes = "Enter whole minutes above 0."; setErrors(found); if (found.title) return titleRef.current.focus(); if (found.minutes) return minutesRef.current.focus(); const id = Date.now(); setCards([...cards, { id, title: title.trim(), column: "todo", minutes: amount }]); setLastAddedId(id); setTitle(""); titleRef.current.focus(); } return ( <main> <h1>Study Board</h1> <form onSubmit={handleSubmit} onKeyDown={(e) => e.key === "Escape" && clearForm()} noValidate> <Field ref={titleRef} label="Title" value={title} onChange={setTitle} error={errors.title} /> <Field ref={minutesRef} label="Minutes" type="number" value={minutes} onChange={setMinutes} error={errors.minutes} /> <button type="submit">Add</button> </form> <ul className="cards" style={{ maxHeight: "9rem", overflowY: "auto" }}> {cards.map((card) => ( <li key={card.id} className={card.id === lastAddedId ? "card selected" : "card"} ref={(node) => { itemsRef.current.set(card.id, node); return () => { itemsRef.current.delete(card.id); }; }} > {card.title} </li> ))} </ul> </main> ); } import { useId } from "react"; // A labelled input. useId gives each instance its own ids, so the label and // the error message point at the right input even when the field is reused. export default function Field({ ref, label, value, onChange, error, type = "text" }) { const id = useId(); const errorId = `${id}-error`; return ( <p> <label htmlFor={id}>{label}</label>{" "} <input ref={ref} id={id} type={type} value={value} onChange={(e) => onChange(e.target.value)} aria-invalid={error ? true : undefined} aria-describedby={error ? errorId : undefined} /> {error && <span id={errorId} className="error"> {error}</span>} </p> ); } export const manyCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, { id: 5, title: "Write reducer tests", column: "todo", minutes: 20 }, { id: 6, title: "Add undo", column: "doing", minutes: 25 }, { id: 7, title: "Split contexts", column: "todo", minutes: 15 }, { id: 8, title: "Use composition", column: "done", minutes: 15 }, { id: 9, title: "Focus a field", column: "todo", minutes: 10 }, { id: 10, title: "Measure renders", column: "todo", minutes: 20 }, { id: 11, title: "Try useTransition", column: "todo", minutes: 25 }, { id: 12, title: "Write a custom hook", column: "todo", minutes: 30 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Check yourself

  1. What's the difference between changing a ref and changing state?
  2. Why can't you call useRef once per item in a list, and what do you do instead?
  3. Why focus the first invalid field after a failed submit?

Was this article helpful?

Your response is saved on this device.