Building Forms in React Using Formik
In this blog post I’ll guide you on how to build forms in React apps using Formik and how the form fields validation handled using Yup.
Dealing with complex forms is one of a challenging problem to solve when developing applications in React. Handling forms in React requires you to write lot of boilerplate codes for form submission, managing and validating user inputs with state and handling error messages.
In order to make form developing easy in React, many libraries have created by developers. In this blog post I am going to show you how to build forms using Formik library.
Formik is a small library. It provides us a reusable form component where we can simply use its API to,
- Handle form submission
- Get values in/out of form state
- Validation and error messages
In this example, I have used Yup for validation. Formik has a special config prop for Yup called validationSchema which will automatically transform Yup’s validation errors into an object.
Now let’s build the form using Formik.
Technologies used:-
- React.js
- Typescript
- Material UI
- Formik
- Yup
- npm
Project Structure
First create a React app using npx create-react-app react-formik-forms — template typescript
Here I have used Typescript to develop this project. Then install Material UI using below command.
npm install @mui/material @emotion/react @emotion/styled
To use Formik in your React project, you need to install it using,
npm install formik
Here’s the sample form that we are going to develop using Formik and MUI with five input fields.
Let’s see how to build this form using Formik. To use Formik, we will first import useFormik hook to our project.
import { useFormik } from "formik";
Formik component accepts props to handle the onSubmit event, initial values and validations. We pass our form’s initialValues
and a submission function onSubmit
to useFormik() hook. Here I have used validationSchema prop in Formik for validations since I’ll be using Yup for validations. (We will look into this later)
The hook then returns the form state and helper methods in a variable called formik.
const formik = useFormik({
enableReinitialize: true,
initialValues: initialValues,
onSubmit,
validationSchema: validationSchema,
});
You can define initial values like below code. Since I am developing with Typescript, I have defined an interface call IUserFormInitialValues for the initial values.
Next, we will write our form using Form component. I have added five fields namely first name, last name, email, address and age.
In above code, I have used some helper methods.
handleSubmit
— A submission handlerhandleChange
— A change handler to pass to each field (TextField, Select etc)handleBlur
— A blur handler to pass to each fieldvalues
— form’s current values
As you can see above, we pass each of these to their respective props and that’s it!. And you will also notice some patterns in the code.
- We reuse the same change handler function, blur function for each input field
- We pass an id and name to each field which matches the properties we defined in initialValues
- We can access the field’s value like for example, email -> formik.values.email
Next, we will implement the onSubmit function. This function will run only when the form values are valid.
const onSubmit = (values: IUserFormInitialValues) => {
console.log(values)
}
Now the form is developed using Formik and left to handle the validation part.
Form Validation using Yup
Now, lets look into form fields validations using Yup. First you need to install it using below command.
npm i yup
Then you have to add validationSchema prop to useFormik and define the validations there. I have created a separate file for validations called ValidationSchema. Below code shows how to handle validations in Yup.
Yup supports all basic validations like string, number, email, phone etc. Therefore, we can easily handle the field validations in React Formik using Yup.
In order to display these validation messages, you can add a div or separate component to display error/validation messages. In this example, I have added a simple div to display error/validation messages under the input field.
{formik.touched.firstName && formik.errors.firstName ? (<div style={{ color: "red" }}>{formik.errors.firstName}</div>) : null}
We can get the errors in Formik form using formik.errors.fieldName
and we can identified whether a field is modified or not by using formik.touched.fieldName
And now the Formik form is complete with validations. You’ve just learned how Formik reduces the amount of code you’ve written to build a form.
Hope you enjoy this blog and find it useful..
Check out the full implementation of this form using 👉 this GitHub link and drop a 👏 if you find this helpful. Thank you and happy coding!😃
#React #Formik #forms #Yup