Formik React Native

Learn via video courses
Topics Covered

Overview

Formik is a widely-used form management library designed for React and React Native applications, offering an easy and effective approach to handling form state, validation, and submission. Although it is primarily associated with React, Formik can also be utilized with React Native to create forms in mobile applications.

This article aims comprehensively understand Formik, including its installation process, API, use cases, and practical examples with corresponding code snippets. By the end, you will have a solid foundation in using Formik to streamline form development in your React and React Native projects.

Introduction

Formik is a popular form management library for React and React Native applications. It simplifies the process of handling forms by providing an intuitive and efficient solution for managing form state, validation, and submission. With Formik, you can easily create and manage complex forms in your React Native projects without the need to write excessive code.

Formik takes care of managing the form state, including handling user input, tracking field values, and managing validation errors. It provides a straightforward API that allows you to define form fields, specify initial values, and set up validation rules using popular validation libraries like Yup.

Features

Formik provides several powerful features that make it an excellent choice for form management in React Native applications. Here are some key features of Formik in the context of React Native:

  • Simplified Form State Management: Formik react native simplifies form state management by tracking and updating field values based on user input.

  • Declarative Validation: Formik react native integrates with validation libraries like Yup allowing you to define validation rules and display error messages for invalid fields.

  • Form Submission Handling: Formik react native provides an easy way to define submission functions and access form data to handle form submission logic.

  • Error Handling and Display: Formik react native tracks validation errors and provides an error object to display error messages alongside form fields.

  • Form Reset and Initialization: Formik react native offers a simple API to reset or initialize the form state, including clearing field values and resetting validation errors.

  • Integration with React Native Components: Formik react native seamlessly integrates with React Native components, enabling you to use familiar input components within your forms.

  • Extensibility and Customization: Formik react native is highly customizable, allowing you to extend its functionality, create custom form components, and integrate with third-party libraries

Installation

To install Formik in your React Native project, you can follow these steps:

  • Open your terminal or command prompt.

  • Navigate to your React Native project directory.

  • Run the following command to install formic and formic react native:

  • Wait for the installation process to complete. Once it's finished, you can start using Formik in your React Native application.

  • Next, we will install two important libraries: yup and recompose.

  • yup is a powerful JavaScript schema validation library commonly used alongside Formik for form validation.

  • recompose is a utility library specifically designed for React/React Native. It offers a collection of higher-order components (HOCs) and utility functions that greatly enhance the functionality and composition of React components.

Guides

This section of the article provides general guidance and instructions for using Formik with React Native. It will include best practices and common scenarios you may encounter when working with Formik in a React Native project.

The Gist

Here's a concise and minimal gist of how to use Formik with React Native:

formik react native Basic Example

Inside the Formik component, we provide the initial form values using the initialValues prop and the handleSubmit function using the onSubmit prop.

The Formik component utilizes the render prop pattern, which allows us to access and utilize various callback functions provided by Formik. Within this pattern, we render the form fields, including two TextInput components for the email and password fields. For each TextInput, we bind the value, onChangeText, and onBlur props to their respective Formik callback functions, such as handleChange and handleBlur.

Custom components

Formik seamlessly integrates with custom components in React Native. You can create your reusable components and connect them to formik react native using the handleChange function to update field values. This allows you to design and use custom input fields, dropdowns, checkboxes, or any other form elements while leveraging Formik's form management capabilities.

formik react native Custom Component

Formatting Inputs

In Formik React Native, you can format inputs as the user types by manipulating the values before rendering them. One common example is adding spaces in a telephone number as the user types. Here's an explanation of how you can achieve this:

  • Define a formatting function:

In this example, the formatPhoneNumber function takes an unformatted phone number as input and returns the formatted phone number. You can implement your specific formatting logic inside this function.

  • Use the Formik component:

formik react native formatting inputs

Move form Above the Keyboard

To create a form in React Native using Formik that moves above the keyboard when it appears, you can use a combination of the KeyboardAvoidingView and ScrollView components. Here's an example of how you can achieve this:

 formik react native inputs with KeyboardAvoidingView

Step by step formik + react-native-formik integration

  • Start with a basic form:
  • Wrap it in formik: formik provides context to the form that we can display in a Text component.
  • connect our input with formik context: To connect your input with Formik context, you can add onChangeText={text => props.setFieldValue("email", text)} on the inputs. Here is an example of how you can do it:
  • On submit pressed: To add a button to submit, you can add a Button component and call the handleSubmit function on the onPress event. Here is an example of how you can do it:
  • Adding validation: We can create a validationSchema with the Javascript library yup and can bring validation to our form. we can also add any custom validation message to the error.
  • Using the react-native-formik library, we can significantly reduce the amount of boilerplate code required for a simple form.

  • Instead of manually adding the onChangeText, onBlur, and error props to each input component, we can utilize the handleTextInput Higher Order Component (HOC) provided by react-native-formik.

  • By wrapping the input component with handleTextInput, the code snippet:

  • can be simplified to just:
  • The handleTextInput HOC takes care of handling the text input'sonChange and onBlur events, as well as automatically displaying the appropriate error message based on the form's state. This significantly reduces the amount of code needed, making the form implementation more concise and efficient.

  • so after using the formik react native library the the code becomes:

  • **handling types of inputs with react-native-formik, we can just add a type to our input
  • Auto focus the next input: React Native Formik provides a convenient way to automatically focus on the next input field within a form. This can be achieved by using two Higher Order Components (HOCs) provided by formik react native:

    1. withNextInputAutoFocusForm: This HOC is applied to the container view that wraps all the input fields within the form. It enables automatic focusing on the next input field when the current one is submitted or filled.
    2. withNextInputAutoFocusInput: This HOC is applied to each individual input component that needs to participate in the automatic focus behavior. However, it requires the input component to be a class and have a focus method defined.

API

formik react native provides a comprehensive API that simplifies the process of building forms in React Native applications. Here are some key components and functions offered by the formik react native API:

handleTextInput

handleTextInput is a set of default higher-order components (HOCs) provided by formik react native specifically for managing text inputs in React Native. It includes a collection of HOCs such as withErrorIfNeeded, withInputTypeProps, and withFormikControl, which are specifically designed for handling text inputs using the React Native TextInput component.

withErrorIfNeeded

This is a higher-order component that is used to display an error message if there is an error in the form field, only if input has been touched or the form has been submitted. It takes two arguments: the name of the field and the error message.

withError

This is a higher-order component that is used to display an error message for a form field. It takes one argument: the error message.

withFocus

This is a higher-order component that is used to focus on a form field when it is rendered. It takes one argument: the name of the field.

withInputTypeProps

When dealing with email inputs in forms, it is common to disable auto-capitalization and use the email keyboard for a better user experience. To simplify this process, formik react native provides the withInputTypeProps higher-order component (HOC).

This is a higher-order component that is used to set props for different input types. It takes one argument: an object containing props for different input types.

withNextInputAutoFocus

The withNextInputAutoFocus functionality, provided by formik react native, allows for automatic focus management between input fields in a form. It simplifies the process of navigating through form inputs and submitting the form when necessary.

To use this feature, the input components should be class components with a focus function, and they need to be wrapped with withNextInputAutoFocusInput. Also, the container holding the inputs should be wrapped with withNextInputAutoFocusForm to handle overall form behavior. This feature enhances the user experience by simplifying form navigation and submission.

withTouched

This is a higher-order component that is used to set the touched state of a form field. It takes one argument: the name of the field.

withPickerValues

The withPickerValues feature in formik react native allows you to wrap your component in a TouchableOpacity that, when pressed, opens a dialog or picker to select a value. This feature is useful when you want to provide a user-friendly way to choose a value from a predefined list of options.

Conclusion

  • Formik is a lightweight form library for ReactJS and React Native.
  • It provides you with a reusable form component that reduces a lot of boilerplate code and simplifies handling the three most annoying parts in the form-building process: getting values in and out of form state, validation and error messages, and handling form submission.
  • Formik is 100% compatible with React Native and React Native Web.
  • It has built-in features for managing form validation, error messages, and form submissions.
  • Formik supports both synchronous and asynchronous form validation.
  • It has support for schema-based, form-level validation from Yup.
  • When working with Formik in React Native, it is important to consider techniques for moving the form above the keyboard to ensure a seamless user experience, utilizing features like KeyboardAvoidingView or custom keyboard handling logic.
  • The integration of Formik with React Native offers a comprehensive solution for managing forms, simplifying the development process, and improving the overall user experience.