Phases of Form Submission with Formik
Learn about the different phases of form submission using Formik.
We'll cover the following...
Implementing form submission
To submit a form we created with Formik, we’ll pass the formik.handleSubmit
method to the onSubmit
event of the form tag.
How will Formik know our form submission logic? We’ll pass an onSubmit
function to the useFormik
hook. This function has a parameter called values
, which is an object that contains the fields in our form represented by their names and their corresponding values, which are the same as the formik.values
object. We’ll write our form submission logic in this function.
* { font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; box-sizing: border-box; margin: 0; padding: 0; transition: 0.6s; } section { width: 100%; max-width: 600px; margin: 0 auto; margin-top: 4rem; } h1 { font-weight: 800; font-size: 2.2rem; color: #303170; margin-bottom: 0.8rem; } p { color: #74728a; font-weight: 500; } form { margin: 3rem 0; } label { font-size: 0.875rem; color: #2e2d44; font-weight: 600; display: block; margin-bottom: 1.4rem; } label small { color: #cf2a2a; } input { display: block; width: 100%; margin-bottom: 0.4rem; border-radius: 8px; padding: 12px 16px; border: 1px solid #ececec; outline: none; margin-top: 0.4rem; font-size: 1rem; } input:focus { border-color: #303170; } button { background: #5f30e1; border-radius: 8px; padding: 12px 20px; outline: none; display: flex; justify-content: center; align-items: center; border: none; font-weight: 600; font-size: 14px; line-height: 22px; color: #ffffff; margin-top: 2rem; cursor: pointer; } button:hover { background: #303170; }
On line 19, we create an onSubmit
function, which accepts a values
parameter. Here, we specify our submission logic. We use JSON.stringify(values)
to convert our values
object to a string and then show it in the alert box in the browser. Next, we log the form values in the console of our browser.
There’s no limit to what we can do in this onSubmit
function. Typically, this is where we’ll do computations on our form values (the values
parameter). At this point, we could also make API requests to send the form values to a server. But we’ll just keep our requests at a minimum ...