Introduction to Form Submission and Validation
Learn how to validate and submit a form in React and how to ensure that all the fields in the form have valid inputs before submission.
We'll cover the following...
Submit the form
After our users have completed the form, they will make an attempt to submit the form. For this, we’ll create a handleSubmit
function that will be called whenever the onSubmit
event of our form is triggered—that is, whenever our users click the “Submit” button.
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; }
On line 27, we listen to the onSubmit
event of our form, and we call the handleSubmit
function when the event fires. This means that whenever our form submits, we call the handleSubmit
function.
But how does the form know when it has been submitted? If we look further down in our app.js file, we see that our “Submit” button has a type
of submit
. This means that whenever the button is clicked, it fires the onSubmit
event of the form that houses it, and the form gets submitted.
Typically, we’re expected to include one button of type submit
in our forms. However, if we have more than one button of type submit
, clicking any of the buttons will trigger the onSubmit
event of our form.
Looking back at our handleSubmit
function on line 19, we use event.preventDefault()
to stop the form from taking its default action when submitted. The default action a form takes when it is ...