React Native + Formik + Yup ❤️

Gustavo Maes
FotonTech
Published in
2 min readNov 27, 2018

--

Every time you start a react native project you probably will go for the mainstream command react-native init, add a few libs you're used to work with, set up eslint prettier and every dev lib that makes your day smoother.

Then you probably will start to work on the designed screens and in 99% of the cases, you will face a form.

A Form is a screen section which allows users to interact with and send controlled/validated informations to a server.

React enables form input controls and validation with the component State and a few tricks. But reinventing the wheel every time you have to build a new form may be a pain in the ass.

That's how Formik was born. It is the logic responsible for validating and controlling your forms to build fast and safe projects.

As an example, we will create a Sign In screen which has two input fields and a button.

Let's install Formik:

> yarn add formik

Now let’s start to make a login form with the Formik component

We start setting initialValues for our inputs.
And Formik handles the inputs control with `handleChange()`

Ok, now that we have the inputs inside Formik, let’s start the magic.

Validation

To validate our values we will use Yup, so let’s install it:

> yarn add yup

Now we can set the validationSchema property in Formik to validate our input fields with yup help.

You can check all available validation options in Yup repository.

You can use a personalized message for each different validation.

Errors

When a required input value doesn't satisfy our validation criteria it should show the user an error by extracting the errors from props which are just an array with the values and their respective error messages.

But we still have a problem here. The error is being displayed before leaving the Input, we will use the prop setFieldTouched to set when the input is onBlur, and check to touched prop to see if we can already show the error.

Form is Valid

Now that we are validating and controlling our Input values we need to check if this is all right to enable the button and call the submit.
And here Formik shines again. We only need to use the prop isValid to enable the button and set the onSubmit and call it with the prop handleSubmit when onPress

Okay, now you have a form with validations, errors and submit.

The finished Sign In screen should look like this:

Formik makes form building much easier and faster
If you have any doubts, do not forget to ask 👽

--

--