My goal is to use a custom component based on Switch
(from React Native) in a Formik form. Here is the code of the form component:
class NewPreferences extends React.Component {
render() {
return(
<View style={styles.mainContainer}>
<View style={styles.newPreferencesContainer}>
<Formik
initialValues={{
food: true
}}
onSubmit={async (values, action) => {
await this.props.onSubmitPress(values)
action.setSubmitting(false)
}}
render={({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
}) => (
<View style={styles.formikNewPreferences}>
<View style={styles.itemRow}>
<Field
source={images.food.uri}
onChange={handleChange('food')}
value={values.food}
name="food"
component={ToggleButton}
/>
</View>
<TouchableOpacity
style={styles.button}
onPress={handleSubmit}
disabled={isSubmitting}
>
<Text>Login</Text>
</TouchableOpacity>
</View>
)}
/>
</View>
</View>
);
}
The component ToggleButton
is the following one:
class ToggleButton extends React.Component<ToggleButtonInterface> {
render() {
return(
<View>
<Image
source={this.props.source}
/>
<Switch
onValueChange={this.props.onChange}
value={this.props.value}
/>
</View>
);
}
}
It appears that toggling the Switch element raises an error: undefined is not an object (evaluating '_a.type')
, in the method _handleChange
of Switch
. Following the documentation of Formik, I thought I simply needed to pass Formik's handleChange
in the props of my custom component, so that when Switch
is toggled, Formik changes its state, which will then change the props value
of Switch
.
Could anyone help me on this issue?
Formik's handleChange expects to be called with a React. ChangeEvent . Since the onValueChange of the Switch component will just be invoked with a boolean you need to use Formik's setFieldValue to handle the change.
Formik is 100% compatible with React Native and React Native Web.
Formik will automagically inject onChange , onBlur , name , and value props of the field designated by the name prop to the (custom) component. children can either be an array of elements (e.g. <option> in the case of <Field as="select"> ) or a callback function (a.k.a render prop).
dirty: boolean Returns true if values are not deeply equal from initial values, false otherwise. dirty is a readonly computed property and should not be mutated directly.
Formik's handleChange
expects to be called with a React.ChangeEvent
.
Since the onValueChange
of the Switch
component will just be invoked with a boolean you need to use Formik's setFieldValue
to handle the change.
<Formik
initialValues={{ switch: false }}
onSubmit={ values => console.log(values) }
>
{props => (
<Switch
value={props.values.switch}
onValueChange={value =>
props.setFieldValue('switch', value)
}
/>
)}
</Formik>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With