In short, Formik offers us methods to handle form inputs that can be set up in no time. Yup helps us to define the validation schema which Formik uses to validate those inputs.
To begin with, we need these things along with React.
MUI v5 — Design form using built-in input components.
Formik — Wrapper to handle form components.
Yup — Define validation schema for form data.
2.Design a simple form using Material UI.
To start off with, we will design a simple form using Material to understand the fundamentals.
I have left the code for the above design below.
3.Create an initial state for the form inputs.
We need an initial state variable for the form inputs used. The use State declaration for the inputs looks like this.
4.Construct validation schema for the form inputs using Yup.
The validation schema can be declared outside the component since it is a one-time declaration.
The validation done for each input is self-explanatory. But, I have left a few comments for clarity.
5.Handle the functionality of the form using Formik.
It’s time for Formik to take control and do the magic we have been waiting for.
First, we have to wrap the form tag using Formik component which will give us access to the methods and data necessary for the form.
That’s it. We are good to go.
You should see validation happening in the fields as expected, which look something like this.
You can refer to the documentation for deeper concepts in form handling which Formik offers.