Handling a CheckBox with Formik and Yup

You can create and validate other field types using Formik and Yup. In this section, you’re going to achieve that by creating a checkbox field that’s quite common when signing up into new applications—a checkbox that asks users to agree to all of their terms and app policies.

Open the Signup.js file and the following checkbox element from the react-native-elements library. It’s going to contain a boolean value. In the initialValues object, please add that.

At the checkbox, there’s a prop called checked that’s required. It holds the current value of the element whether it’s checked or not. After you have defined the confirmPassword input field, please state the following:

The required prop checked changes the icon to check or uncheck. By default, it will be marked uncheck. The uncheckedIcon prop takes the value of an icon. The title prop's value of the checkbox, when marked check, changes to the value of checkedTitle . These are advantages of using a component library like react-native-elements .

Using the setFieldValue from Formik props, you can set the value of the check to true or false. It accepts the reference of the key check itself as the first parameter. !values.check states the opposite of the current value of the key check .

Lastly, edit the validationSchema by adding the key check . It’s going to use a boolean schema type.

The following demonstration shows how this works in practice:

Bonus: Hide/Show Password fields

In this section, you’re going to add the ability to hide or show the password on the corresponding field. By the end of this section, the password input field is going to look like this.

To start, open the Login.js file and import TouchableOpacity from react-native and Ionicons from Expo's vector icons library, which comes with Expo SDK.

The next step is to define an initial state inside the Login component. This will help track of the current icon being shown and the visibility of the password.

Then define a handler method that will trigger on the onPress prop of TouchableOpacity . This will check the previous state of the icon and the password's visibility field.

Then go to the password input field and add the prop rightIcon from react-native-elements . You’re going to pass the TouchableOpacity prop for the icon to be touchable and trigger a function (in this case, handlePasswordVisibility ).

Also, we need to tame the prop secureEntryText . It accepts a boolean as its value, and that’s what passwordVisibility is. If its value is true, which is the initial state, it will secure the password field entry. When the icon is clicked, the visibility is going to change to false , and then the password will be shown.

This is the output you’re going to get:

Conclusion

That’s it. This post and the previous one covers enough to get you started with creating advanced forms in React Native apps using Formik and Yup.