I want to create an abstraction of form component in React native, something like:
import { useForm, FormProvider, UseFormProps,} from 'react-hook-form';// I change resolver value to yup validation schema by defaulttype FormProps<TFieldValues> = Omit<UseFormProps<TFieldValues>, 'resolver'> & { children: React.ReactNode; validationSchema: Yup.AnyObjectSchema;};function Form<TFieldValues extends FieldValues = FieldValues>({ defaultValues, validationSchema, children,}: FormProps<TFieldValues>) { const methods = useForm<TFieldValues>({ defaultValues, resolver: yupResolver(validationSchema), }); return <FormProvider {...methods}>{children}</FormProvider>;}
the idea is to use this Form
component as a wrapper for form elements such as:
TextFieldsSubmitButtonCheckbox/Radios... and so on
these form elements are simply abstractions that consume FormContextProvider
with useFormContext
, something like:
import { FieldValues, useFormContext, SubmitHandler } from 'react-hook-form';import { Pressable, Text } from 'react-native';type ButtonProps = PressableProps & { onSubmit: SubmitHandler<FieldValues>;};function SubmitButton({ onSubmit, ...RestButtonProps }: ButtonProps) { const { handleSubmit } = useFormContext(); return (<Pressable {...RestButtonProps} onPress={handleSubmit(onSubmit)}><Text>Submit</Text></Pressable> );}
the problem I'm having is when I try to combine everything in a form(Form component and form elements), I get type problems:
type LoginFormValues = { email: string; password: string;};function LoginForm() { const handleSubmit: SubmitHandler<LoginFormValues> = ({ email, password }) => console.warn(email, password); return (<Form defaultValues={defaultValues} validationSchema={validationSchema}> {/* here are the other elements of the form */}<SubmitButton title="Sign In" onSubmit={handleSubmit} /></Form> );}
onSubmit
handler throwns an error:
TS2322: Type 'SubmitHandler<LoginFormValues>' is not assignable to type 'SubmitHandler<FieldValues>'. Type 'FieldValues' is missing the following properties from type 'LoginFormValues': email, password
I don't know if I'm using the RHF types wrong or if I'm getting something wrong. I did not find anything similar in the RHF documentation.