CodeBlanks Logo Icon CodeBlanks

Summary - Forms

Write a short contact form with a name input.

Summary - Forms

In this group you learned React forms. A controlled input has its value bound to state; onChange updates state on each keystroke. The single source of truth is state.

Form submit uses onSubmit and e.preventDefault(). Several fields are managed with one object state + spread.

Later we will lighten this with React Hook Form; for now the basics are enough.

Practice Forms summary task

Complete the skeleton. Write a SearchForm component; import useState. Define const [q, setQ] = useState("");. handleSubmit (parameter e) calls e.preventDefault(). Return a <form onSubmit={handleSubmit}> with <input value={q} onChange={e => setQ(e.target.value)} /> and <button type="submit">Search</button>. Export it.

Starter code

App.jsx
import { useState } from "react";

// Define SearchForm here

Sample solution

App.jsx
import { useState } from "react";

function SearchForm() {
  const [q, setQ] = useState("");
  function handleSubmit(e) { e.preventDefault(); }
  return <form onSubmit={handleSubmit}><input value={q} onChange={e => setQ(e.target.value)} /><button type="submit">Search</button></form>;
}

export default SearchForm;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is wrong?

App.jsx
preventDefault stops the reload.
  • value is bound to state
  • preventDefault is not needed on submit Correct answer
  • object state updates with spread
  • onChange runs on each keystroke

Explanation: preventDefault is always needed; otherwise the page reloads.

2 Summary - Forms: match the terms

Term Meaning
value State source
onChange Change
onSubmit Submit
preventDefault Stop reload

All lessons in Beginner