In our modern web, forms are a very crucial part of the web, we use it to collect data from users. Forms can be used to onboard users on a platform, for surveys, etc.
However, managing form state, validation, and submission logic can often become cumbersome and error-prone, especially as forms grow in complexity
Formik
Formik is an awesome library that helps you to manage form states, validations, and other amazing features like showing the number of characters a user is giving to the input field while they are typing.
In this article, we are going to explore Formik, how to use it for form validation, submission logic, and how easy it is to manage form states.
Prerequisites you need to understand this article
1.Basic knowledge of React js.
2.Basic understanding of how form works in React js.
3.Basic understanding of javascript.
4.You must have Node js installed on your computer (for your React application to run)
5.And finally, a web browser like Google Chrome.
For this article, I will be using an online code editor called Codesandbox. You can go ahead and use it as well, you can also create normal React js application on your computer.
Codesandbox is an online code editor that allows developers to write code on the web even without their laptops. It safes a lot of time, instead of installing React js, Next js or any other framework, codesandbox allows you to choose them in seconds insteading of wasting time to install them. It allows you to equally select libraries too in seconds. This is amazing right? The most interesting part is that it has free version you can use
Installation
For us to use Formik, we have to install it before we could use it.
npm install formik --save
We also have to install another library called yup, yup will help us to validate the input fields based on our preference. We can decide how long an input field should be, the characters it must contain etc.
npm i yup
After that, we can setup the formik and start connecting it with our form.
import { useFormik } from 'formik';
import * as yup from "yup";
const formik = useFormik({
enableReinitialize: true,
initialValues: {
name: "",
surname: "",
number: "",
},
validationSchema: yup.object({
name: yup
.string()
.trim()
.max(10, "name cannot be more than 10 characters"),
surname: yup
.string()
.trim()
.max(10, "Surname cannot be more than 10 characters"),
number: yup
.string()
.trim()
.max(5, "Your number cannot be more than 5 digits"),
}),
onSubmit: (values) => {},
});
You can clearly see how I used yup to decide how long an input field should be, you can also checkmate passwords, links, etc. with Yup.
Let`s create the form
We have to create the form and connect the input fields with the Formik, we have to make sure that the name we are giving the input fields matches with its reference in Formik initialValues.
Check the input field below, you can clearly see that the name is qual to the name in the initialValues on the formik setup. Without this, you might experience issues with your input field.
<input
type="text"
placeholder="Your name"
name="name"
value={formik.values.name}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
`
import * as yup from "yup";
import { useFormik } from "formik";
import { useState } from 'react';
export default function Form() {
const [isSubmitting, setIsSubmitting] = useState(false);
const [submissionError, setSubmissionError] = useState(null);
const formik = useFormik({
enableReinitialize: true,
initialValues: {
name: "",
surname: "",
number: "",
},
validationSchema: yup.object({
name: yup
.string()
.trim()
.max(10, "name cannot be more than 10 characters"),
surname: yup
.string()
.trim()
.max(10, "Surname cannot be more than 10 characters"),
number: yup
.string()
.trim()
.max(5, "Your number cannot be more than 5 digits"),
}),
onSubmit: async (values) => {
setIsSubmitting(true);
setSubmissionError(null);
try {
const response = await axios.post('/api/submit', values);
console.log('Form submitted successfully:', response.data);
// Optionally reset form
formik.resetForm();
} catch (error) {
setSubmissionError(error.message || 'Failed to submit form');
} finally {
setIsSubmitting(false);
}
},
});
return (
{/* label con */}
Your name
{formik.values.name.length}/10
{/* input control */}
<div className="input-control">
<input
type="text"
placeholder="Your name"
name="name"
value={formik.values.name}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
</div>
{formik.touched.name && formik.errors.name && (
<div className="error">{formik.errors.name}</div>
)}
</div>
{/* surname con */}
<div>
{/* label con */}
<div className="flex-con">
<label htmlFor="">Your surname</label>
<h6>{formik.values.surname.length}/10</h6>
</div>
{/* input control */}
<div className="input-control">
<input
type="text"
placeholder="Your surname"
name="surname"
value={formik.values.surname}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
</div>
{formik.touched.surname && formik.errors.surname && (
<div className="error">{formik.errors.surname}</div>
)}
</div>
{/* number con */}
<div>
<div className="flex-con">
<label htmlFor="">Your number</label>
<h6>{formik.values.number.toString().length}/5</h6>
</div>
{/* input control */}
<div className="input-control">
<input
type="number"
placeholder="Your number"
name="number"
value={formik.values.number}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
</div>
{formik.touched.number && formik.errors.number && (
<div className="error">{formik.errors.number}</div>
)}
</div>
<button
className={` ${formik.dirty ? "btn" : "btn-grey"}`}
type="button"
disabled={isSubmitting || !(formik.isValid && formik.dirty)}
>
{isSubmitting ? 'Submitting...' : 'Send'}
</button>
</form>
</main>
);
}
`
The enableReinitialize
The enableReinitialize option in the useFormik hook is a crucial feature that allows Formik to reinitialize the form state with new initial values. By default, Formik only initializes the form state once, and subsequent changes to the initial values will not be reflected in the form state. By setting enableReinitialize to true, Formik will reinitialize the form state with new initial values whenever the initialValues prop changes. This is particularly useful when working with dynamic forms, where the initial values may change based on user interactions or other application state changes. By enabling reinitialization, you can ensure that your form state remains up-to-date and accurate, even as the initial values change.
Value
You can clearly see how we are accessing the value of each input field from Formik in real time without using any useState.
Make sure that you are really accessing the right state, as you can see from the example, we are correctly accessing each state value.
Onchange
We are using the built-in onChange function in Formik to update each input state while the user is typing. So we dont really need to create anything else, that
s cool right 😊?
OnBlur
We are also using the onBlur function in formik to let Formik know when an input field loses focus so that it can check if a user is actually giving the right input value.
The error message
We display the error message we specified in yup for each input field whenever the input field doesn`t match with our validation. You can clearly see that in the code.
The length of the input value
We can also show the length of an input value while a user is typing, this will help users to know the length of what they are typing.
The button
The style of the button is dynamic, when all the input fields are empty, the button will have some certain kind of style. But when we have a value in one of the input fields, the style of the button changes as well.
The button is also disabled if we don`t have any value in the input fields and the content of the button is dynamic too. We also disable the button when we are submitting the form data.
This will prevent users from submitting empty forms.
OnSubmit
The submit function allows us to send the form data to our desired endpoint or location. You can write any logic there, just make sure that the submit function is connected to the form so that it can be triggered when a user clicks on the send button.
In our case, we are trying to send the form data to an endpoint, although it`s not real. But the logic is sending the form data to an endpoint with the help of Axios.
As you can see, it`s very easy to manage and validate form values with Formik.
Conclusion
Managing form states and validation are very essential steps to making sure that we are actually getting the right data from users but doing this is usually not a work in the park.
Formik is a very amazing library that helps us to manage form data effectively, it also has other amazing features like getting the length of an input value, the handleChange function, the handleBlur function, error messages, etc.
With the combination of yup, we can actually validate the input values based on our preference.
I hope you now understand the basics of Formik and how to verify forms with Formik and Yup.
You can study more about Formik here and Yup here.
Happy coding 😊!
Top comments (0)