This is part 2 of the tutorial. Please read basic usage of useFormik hook with React Form(1) first.
Let’s continue with the code in last tutorial.
Now, we add a new validation for field lname
, and see what will happen.
When we just type in first name, the error of last name appeared. This is not what we want, we should check whether the input box has been touched, if the user has not yet touched the input box, we should not show the error.
In useFormik
you can just add onBlur={formik.handleBlur}
to the input field, then get the value by formik.touched.(input field name)
, it will be true if user has touched that input field. You can see the code below to understand how to use it.
We need to add the name
, onChange
, value
, onBlur
, it becomes a little bit cumbersome, with formik
,we can simply use one magic code: {...formik.getFieldProps(‘field name’)}
, it will return 4 properties.
Below is the complete code.
Be careful, when we work with radio
input type, the position of {...formik.getFieldProps(‘field name’)}
is important. If we place it after value="male"
in this example, since we do not set initial value,{...formik.getFieldProps(‘field name’)}
will return value:""
and it will override our value="male"
, then the form will not work.