The search box
Keep the search field in state, and submit it without reloading the preview.
An input that React cannot see
Here is the watchlist as you left it. Three cards, a heading, a count.
You need a box to type a show name. An <input> with no value lets
you type. React never hears those keystrokes.
query starts as "". The line under the box reads that state.
Type a name. The box fills in. The line still says (empty).
value and onChange
Pass query as value, and write every keystroke back with
onChange. That is the same round trip as the Watched checkbox, with
value instead of checked.
const [query, setQuery] = useState("") is the same hook as A
component's memory.
Type a name. The line under the box follows every keystroke.
An input that React both reads and writes is a controlled input. Drop
onChange and the box freezes, because value never changes.
Search is a form
Move the box into /SearchForm.js. It receives query,
onQueryChange, and onSearch, the same props-down pattern as
Passing handlers down.
Put onSubmit on the <form> so Enter works. A form's default is to
send itself and reload the page. Call event.preventDefault() first,
as in Propagation and defaults, then call
onSearch().
App keeps query. Submit copies it into submittedQuery. The list
does not change yet.
Type a name and press Search. The line reads Looking for: plus what
you typed. The three cards stay.
Common mistakes
valuewithoutonChange. React keeps showing the old string, so you cannot type. Pair them.- Calling
onSearch()during render. WriteonSearch={handleSearch}, notonSearch={handleSearch()}. - Forgetting
preventDefault. The browser reloads the preview and the cards disappear.
Exercise
Search is wired up, but pressing Search reloads the preview. The cards vanish, so the line never appears.
Stop the form's default. Then type severance and press Search.
A line should read:
Looking for: severance
The three cards stay on screen.
Hint: handleSearch needs the event. Call event.preventDefault()
before onSearch().