Start learning free

LESSON 71 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

A Controlled Input

Practice

Right now the search field keeps its own text. The visitor can type in it, but the query state in ProductList never hears about it, so nothing else on the page can use what was typed. In a controlled input, React owns the text: the field shows a state value, and every key is sent back to that state.

Two props do it. value says what the field shows. onChange runs on every key, and event.target.value is the field's text with the new key in it. Here is a coupon field with its own state:

const [coupon, setCoupon] = useState("");

<input aria-label="Coupon" value={coupon}
  onChange={(event) => setCoupon(event.target.value)} />

A key calls setCoupon, React draws the component again, and value puts the new text in the field. A field with value but no onChange is read-only: React undoes every key and prints a warning. And since the text lives in state, emptying the state empties the field.

SearchBox gets query and setQuery as props from the given ProductList.jsx. The check must see:

> open the page
    field "Search": "" (placeholder "Search products")
    button: Clear
> type "mug" into "Search"
  + field "Search": "mug"
> click "Clear"
  + field "Search": "" (placeholder "Search products")

Your task: in src/SearchBox.jsx, give the input value={query} and an onChange that calls setQuery with the new text. Then add a Clear button that sets the query to "".


Assignment
Follow the Coding Tutorial to turn the search field in src/SearchBox.jsx into a controlled input and add a Clear button.


Hint
Put the Clear button's setQuery("") inside an arrow function, () => …, so it runs when the button is clicked, not while it is drawn.


STEP 1 OF 3
    Ctrl + Enter to check