Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Form Submission | Formik
Expert React
course content

Course Content

Expert React

Form Submission

Step 8: Implement the form submission

We will use Formik's onSubmit property to handle the form submission logic. As we don't have an actual backend, we will simulate the submission by alerting the form data and displaying it in the console.

Code exaplanation:

  • Line 6: We define the onSubmit callback function that takes two arguments: values and { resetForm }. The values argument contains the current values of the form fields.
  • Line 7-8: We extract the username and occupation values from the values object and assign them to the variables userName and userOccupation, respectively.
  • Line 9: The console.log statement logs a message to the console, displaying the user's name and occupation. Template literals are used to concatenate the values of userName and userOccupation into the log message.
  • Line 10: The alert function displays a pop-up alert with the user's name and occupation, visually confirming the form submission.
  • Line 11: The resetForm function is called to reset the form fields to their initial values. By calling resetForm(), the form fields will be updated with the initial values specified in the initialValues object.

Note

If you attempt to manually reset the form by assigning empty strings ("") as the initial values, it won't work, and the form fields will retain their current values. Instead, use the resetForm function provided by Formik to ensure proper form reset.

Complete code

Feel free to examine the complete app code to understand better how the form submission logic is implemented and see the code in action.

Everything was clear?

Section 4. Chapter 6
We're sorry to hear that something went wrong. What happened?
some-alt