React: A search form with submit and reset

Forms have their own events. Handle submitting and resetting without reloading the page.

What to build

A search form that reports its search and can be reset.

Requirements

  • Render a form with an input named q, a select named category with the options all, books and music (starting at all), a submit button Search and a button Reset that does not submit.
  • On submit, without reloading, print Search: Q in CATEGORY, or Type something first if the search text is empty (after trimming spaces).
  • Reset puts the form back to its starting values and prints Reset.

Constraints

Do not use state; read the values from the form.

Example

Typing "jazz", choosing music and pressing Search prints "Search: jazz in music".

Why it works

preventDefault keeps the page, the form's elements give the current values when they are needed, and a button of type button is the way to add an action to a form that is not a submit.

Hints

Hint 1

In onSubmit, call event.preventDefault() and read event.target.elements.q.value and .category.value.

Hint 2

A button with type="button" does not submit; its onClick can call event.currentTarget.form.reset().

Solution

Show one correct solution (try it yourself first)
export default function App() {
  function handleSubmit(event) {
    event.preventDefault();
    const { q, category } = event.target.elements;
    const text = q.value.trim();
    console.log(text ? "Search: " + text + " in " + category.value : "Type something first");
  }

  function handleReset(event) {
    event.currentTarget.form.reset();
    console.log("Reset");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="q" />
      <select name="category" defaultValue="all">
        <option value="all">all</option>
        <option value="books">books</option>
        <option value="music">music</option>
      </select>
      <button type="submit">Search</button>
      <button type="button" onClick={handleReset}>
        Reset
      </button>
    </form>
  );
}

Lesson: Responding to events →