Formik
Form are one the most important component of a website. We use formik in our project to handle our forms.
Formik is a small library that helps you with the 3 most annoying parts:
- Getting values in and out of form state
- Validation and error messages
- Handling form submission
Without Formik#
React uses controlled components to implement forms.
Below we see how we handle multiple inputs
An input form element whose value is controlled by React in this way is called a “controlled component”.
This allows us to store the form state in our app and share with other components, if needed.This is all what we can do with React.
React leaves rest of the work upto us, to manage Error Messages, Validation, Testing, etc. It's okay as React is just the "view".
Installation#
You are free to write your own validation logic. Formik recommends using Yup.
We'll also be using Yup library for our validation logic.
Usage#
With Formik, you can and should build reusable input primitive components that you can share around your application.
In our project we create these sharable input component inside form folder located at src/app/common/form/
MyTextInput.jsx
useField()returns[formik.getFieldProps(), formik.getFieldMeta()]which we can spread on<input>. We can use fieldmetato show an error message if the field is invalid and it has been touched (i.e. visited)
useField() will implicitly grab the respective onChange, onBlur, value props and pass them to the element.
tip
It is recommended that you go through the well documented tutorial on Formik docs
Using our shareable input component#
Below is our code snippet taken from AccountPage.jsx file.
Let's discuss the unfamiliar thinks in the above code one by one.
Following are the render props passed by <Formik /> component,
A render prop is a function prop that a component uses to know what to render.
isValid: booleanReturns
trueif there are noerrors(i.e theerrorsobject is empty) andfalseotherwise.isSubmitting: booleanReturns
trueif submission is in progress andfalseotherwise.dirty: booleanReturns
trueif values are not deeply equal from initial values,falseotherwise.
Useful Resources#
- Forms in React
- Formik docs
- Render Props
- Blog on render props
