- We have a 3rd party component that we want to use
SecondaryInput - Want to use
Yupvalidation (don't know how to use yup with the rule props, inControllercomponent) - Controlled component is inside the child component so I am using the
useFormContext - Schema code is not working
My code is something like this
NOTE: I can not use the ref inside the custom component as it does not take props like ref
Parent component
const schema = yup.object().shape({
patientIdentity: yup.object().shape({
firstName: yup.string().required('Required field'),
lastName: yup.string().required('Required field'),
}),
});
const methods = useForm();
const {
errors,
handleSubmit,
register,
setValue,
reset,
getValues,
} = useForm({
defaultValues: {
patientIdentity: {
firstName: 'test 1',
lastName: 'Test 2',
},
},
validationSchema: schema,
});
const onSubmit = (data, e) => {
console.log('onSubmit');
console.log(data, e);
};
const onError = (errors, e) => {
console.log('onError');
console.log(errors, e);
};
console.log('errors', errors); // Not able to see any any error
console.log('getValues:> ', getValues()); Not able to see any any values
return (
<View style={[t.flex1]}>
{/* Removed code from here */}
<View style={[t.flex1, t.selfCenter]}>
<FormProvider {...methods}>
<View style={[t.flexCol]}>
<PatientForm /> // <<Child component
<PrimaryButton
style={[t.pL3, t.h10]}
onPress={handleSubmit(onSubmit, onError)}
>
Save changes
</PrimaryButton>
</View>
</FormProvider>
</Row>
</View>
Child component
const {
control,
register,
getValues,
setValue,
errors,
defaultValuesRef,
} = useFormContext();
console.log('errors:>>', errors); // NOt able to log
console.log('Identity | getValues>', getValues());
return (
<DetailCard title="Identity">
<Controller
control={control}
render={(props) => {
const { onChange, onBlur, value } = props;
return (
<SecondaryInput
label="Legal First Name"
value={value}
onTextChange={(value) => onChange(value)}
onBlur={onBlur}
/>
);
}}
name="patientIdentity.firstName"
rule={register({
required: ' name cannot be empty',
})}
defaultValue=""
/>
<Controller
control={control}
as={({ onChange, onBlur, value }) => {
return (
<SecondaryInput
label="Legal Last Name"
value={value}
onTextChange={(value) => onChange(value)}
onBlur={onBlur}
/>
);
}}
name="patientIdentity.lastName"
rules={{
required: 'this is required field',
message: 'required field',
}}
defaultValue=""
/>
</DetailCard>
)