React Native
Formik is 100% compatible with React Native and React Native Web. However, because of differences between ReactDOM's and React Native's handling of forms and text input, there are some differences to be aware of. This section will walk you through them and what we consider to be best practices.
The gist
Before going any further, here's a super minimal gist of how to use Formik with React Native that demonstrates the key differences:
// Formik x React Native example
import React from 'react';
import { Button, TextInput, View } from 'react-native';
import { Formik } from 'formik';
export const MyReactNativeForm = props => (
<Formik
initialValues={{ email: '' }}
onSubmit={values => console.log(values)}
>
{props => (
<View>
<TextInput
onChangeText={props.handleChange('email')}
onBlur={props.handleBlur('email')}
value={props.values.email}
/>
<Button onPress={props.handleSubmit} title="Submit" />
</View>
)}
</Formik>
);
As you can see above, the notable differences between using Formik with React DOM and React Native are:
- Formik's
props.handleSubmit
is passed to a<Button onPress={...} />
instead of HTML<form onSubmit={...} />
component (since there is no<form />
element in React Native). <TextInput />
uses Formik'sprops.handleChange(fieldName)
andhandleBlur(fieldName)
instead of directly assigning the callbacks to props, because we have to get thefieldName
from somewhere and with React Native we can't get it automatically like in web (using input name attribute). You can also usesetFieldValue(fieldName, value)
andsetFieldTouched(fieldName, bool)
as an alternative.