Form events
- React course
- Beginner
- Lesson 38/84
- 4 min
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
// Define SignupForm hereSample solution
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?
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
function handleSubmit(e) { ____; /* process */ }
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 |