CodeBlanks Logo Icon CodeBlanks

Form events

Learn to catch input change and form submit events.

Form events

When a form is submitted the browser reloads the page. In React we stop that: inside the handler we call e.preventDefault().

You write onSubmit={handleSubmit} on the form tag. The handler takes e and first calls e.preventDefault(); then does its work.

This way the form can process data without a page reload. This is the basis of modern React forms.

Submit button

Inside the form you write <button type="submit">Send</button>; the button submits the form. type="submit" is the default but writing it is still good.

Instead of adding onClick to the button, listening to the form's onSubmit is cleaner; the Enter key also submits.

This pattern builds accessible forms that work with both keyboard and mouse.

Practice Form skeleton

Complete the skeleton. Write a SignupForm component; define handleSubmit taking e; its first line calls e.preventDefault(). Return a <form onSubmit={handleSubmit}> containing an <input /> and <button type="submit">Send</button>. Export it.

Starter code

App.jsx
// Define SignupForm here

Sample solution

App.jsx
function SignupForm() {
  function handleSubmit(e) { e.preventDefault(); }
  return <form onSubmit={handleSubmit}><input /><button type="submit">Send</button></form>;
}

export default SignupForm;

Questions and answers

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

1 What stops the page reload on submit?

App.jsx
preventDefault cancels the browser default behavior.
  • e.preventDefault() Correct answer
  • e.stopPropagation()
  • return false
  • form reload

Explanation: e.preventDefault() stops the default reload.

2 Form events: fill in the missing part

Question
function handleSubmit(e) { ____; /* process */ }
Answer
function handleSubmit(e) { e.preventDefault(); /* process */ }

Explanation: You stopped the default first.

3 Form events: match the terms

Term Meaning
onSubmit Form submit
e.preventDefault() Stops reload
type="submit" Submit button
input Data field

All lessons in Beginner