formik
formik copied to clipboard
Using Field with as is blocking input
When I use Formik with the Field component, wrapping another component, I can't input anything. I am using a component from NativeBase, in my project, but also using TextInput from React Native yields the same results. As an example I prepared a snack where this is showcased exactly how I am experiencing this issue. https://snack.expo.dev/@ricohumme/formik-field-as-component-example
Your environment
| Software | Version(s) |
|---|---|
| Formik | 2.2.9 |
| React | 17.0.1 |
| NativeBase | 3.3.7 |
| TypeScript | 4.6.3 |
| Browser | Chrome |
| npm/Yarn | 1.22.17 |
| Operating System | Ubuntu 18.04 |
The Field component doesn't work in React Native, you'll instead need to connect the Input or TextInput components to Formik's API using handleChange, etc.
https://formik.org/docs/guides/react-native
(I have plans for this...)
The whole reason I switched to the Field component is because I have a form with an array of objects in them. So I looked at the FieldArray component. How would I go down that road? I can't seem to find an example which would let me use the path of element other than using the name prop within a component of FieldArray (parent.index.childprop)
If I'm not mistaken (I don't have Formik in front of me) you can do something like:
import { getIn, useFormikContext, FieldHookConfig, Formik, FieldArray } from 'formik';
const MyNativeField = (props: FieldHookConfig) => {
const formik = useFormikContext();
return <TextInput
onChangeText={formik.handleChange(props.name)}
onBlur={formik.handleBlur(props.name)}
value={getIn(props.values, props.name)}
/>
}
const myFormWithArray = () => (
<Formik {...formikProps}>
<FieldArray name="parentField">
{(props) => (
/* and like, add, remove, etc */
<MyNativeField name={`${props.name}.1} />
<MyNativeField name={`${props.name}.2} />
<MyNativeField name={`${props.name}.3} />
)}
</FieldArray>
</Formik>
);