Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formik + yup and validating fields that are in a child react component

lets say i have the following code:

let addressSchema = yup.object().shape({
  firstname: yup.string().required().max(35),
  lastname: yup.string().required().max(35),
  company: yup.string().max(35),
  address1: yup.string().required().max(35),
  address2: yup.string().max(35),
  city: yup.string().required(),
  stateId: yup.string().required(),
  zipcode: yup.string().required().length(5),
  phone: yup.string().required().matches(phoneRegex, 'Phone number is not valid')
});

let checkoutFormSchema = yup.object().shape({
  email: yup.string().email().required(),
  billAddressAttributes: addressSchema,
  shipAddressAttributes: addressSchema,
});

<Formik
    initialValues={this.buildInitialValues()}
    onSubmit={(values, actions) => {
    }}
    validationSchema={checkoutFormSchema}
>
    {formikProps => (
        <FieldWrapper
            Label={<Label placement="left">Email address</Label>}
            Input={<Field type="email" name="email" component={Input} />}
        />
        <AddressFormFields prefix="billAddressAttributes" />
        <AddressFormFields prefix="shipAddressAttributes" />
        )}
</Formik>

where <AddressForm/> has a bunch of formik <Field/> components for the address, like how the email field is being made.

The email field works fine, triggering all events and properly showing the validation errors, but i cant get any of the formik <Field/> in the <AddressForm/> to trigger any events like touch, or show validation errors. I am guessing its because the formikProps isnt being passed down to the <AddressForm/>, but I can't figure out what to do. I've searched thoroughly through the documentation and stackoverflow but i couldn't find any examples of how to do this.

like image 595
Zyren Avatar asked Nov 16 '22 07:11

Zyren


1 Answers

AddressForm should have the context as it's placed inside the Formik component. Perhaps, you've made some mistakes in manipulating fields' names and prefixes. Here is the working example of the nested form:

https://codesandbox.io/s/formik-nested-fields-1nvkj

like image 177
teimurjan Avatar answered Dec 05 '22 05:12

teimurjan