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'serrorprop, 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
selectedclass. - 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.
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
Runs with Vite on your computer: unzip, then
npm install and npm run dev. Check yourself
- What's the difference between changing a ref and changing state?
- Why can't you call
useRefonce per item in a list, and what do you do instead? - Why focus the first invalid field after a failed submit?
Completion is saved in this browser only. It does not measure mastery.