Handling form in react can be really verbose. We need to manage form state and update it when input changed, we also need to validate the form and show the validation message before submitting the form.
Today, I would like to introduce Formik library to simplify above process:
Formik is a small library that helps you with the 3 most annoying parts:
1.Getting values in and out of form state
2.Validation and error messages
3.Handling form submission
We will use below example form to demo some basic usage of useFormik.
In react, we need to make the HTML form elements as “Controlled Components”, we typically maintain their own state and update it based on user input by creating various onChange
function in each <input/>
element and map the value to the state.
By using useFormik, we can put in an object with property initialValues
, add onChange={formik.handleChange}
in input as formik.handleChange
will automatically update the value based on the name
of the <input/>
. For the text input, we can get the the form value fromformik.values
and map it to the value props as below:
For the validation and submition, we can add the properties validate
and onSubmit
in useFormik
as below:
In here, I just demo the validation of field fname
. It is more easier to build the validation check by Yup.
By default, each time calling onChange
andonSubmit
,Formik will invoke validate
, only when errors
is empty object, the form will be sent out.
Part2: https://medium.com/@frankie95/basic-usage-of-useformik-hook-with-react-form-2-c8f44e272051