CodeBlanks Logo Icon CodeBlanks

Form submission

Learn to catch form submission and read the data.

Form submit

You can put controlled inputs in a form and process them at once with onSubmit. The handler stops the reload with e.preventDefault(), then reads the state.

Each input is a separate piece of state; on submit you gather them and process. This is the basis of multi-field forms.

A submit button with type="submit" triggers the form onSubmit; Enter works too.

Multi-field form

You keep several fields either in separate useState calls or in one object state. With the object approach you update with spread.

Example: setForm(f => ({...f, name: e.target.value})). This saves you from writing a handler per input; one handleChange is enough.

Later we will lighten this load with React Hook Form; for now we learn the basic approach.

Practice Submit form

Complete the skeleton. Write a GreetForm component; import useState. Define const [name, setName] = useState("");. handleSubmit (parameter e) calls e.preventDefault() on its first line. Return a <form onSubmit={handleSubmit}> with <input value={name} onChange={e => setName(e.target.value)} /> and <button type="submit">Send</button> inside. Export it.

Starter code

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

// Define GreetForm here

Sample solution

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

function GreetForm() {
  const [name, setName] = useState("");
  function handleSubmit(e) { e.preventDefault(); }
  return <form onSubmit={handleSubmit}><input value={name} onChange={e => setName(e.target.value)} /><button type="submit">Send</button></form>;
}

export default GreetForm;

Questions and answers

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

1 What should be the first thing on submit?

App.jsx
preventDefault stops the browser reload.
  • Update state
  • A fetch call
  • Render
  • e.preventDefault() Correct answer

Explanation: First stop the page reload.

2 Form submission: fill in the missing part

Question
function handleSubmit(e) { ____; send(text); }
Answer
function handleSubmit(e) { e.preventDefault(); send(text); }

Explanation: You stopped the default first.

3 Form submission: match the terms

Term Meaning
onSubmit Form submit
e.preventDefault() Stops reload
type="submit" Submit button
setForm({...f}) Object update

All lessons in Beginner