Skip to content

Instantly share code, notes, and snippets.

@jgcmarins
Last active April 5, 2021 00:49
Show Gist options
  • Save jgcmarins/969f1d140a078c83745addbe749ad17f to your computer and use it in GitHub Desktop.
Save jgcmarins/969f1d140a078c83745addbe749ad17f to your computer and use it in GitHub Desktop.
React Native + Formik hooks example
import React from 'react'
import { FormikProvider, useFormik } from 'formik'
import * as yup from 'yup'
import TextInputFormik from './TextInputFormik'
const ReactNativeFormikExample: React.FC<unknown> = (props) => {
const formik = useFormik({
initialValues: {
name: '',
},
// @TODO - render errors
validationSchema: yup.object().shape({
name: yup.string().required('Name is required'),
}),
onSubmit: (values) => {
// do whatever you want with form values
},
})
return (
<>
<FormikProvider value={formik}>
<TextInputFormik
name="name"
placeholder={'Name'}
/>
</FormikProvider>
<TouchableOpacity onPress={formik.handleSubmit} disabled={!formik.isValid || Object.keys(formik.errors).length > 0} />
</>
)
}
export default ReactNativeFormikExample;
import React from 'react';
import { TextInput } from 'react-native';
import { useField } from 'formik';
const TextInputFormik = (props: React.ComponentProps<typeof TextInput>): React.ReactElement => {
const [field] = useField(props.name)
return <TextInput {...props} value={field.value} />
}
export default TextInputFormik;
@sibelius
Copy link

this does not make much sense, you should provide the field name, and let useField get the rest of even handlers

onChangeText={formik.handleChange('name')}
          onBlur={formik.handleBlur('name')}
          value={formik.values.name}

@jgcmarins
Copy link
Author

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment