Adharsh M
Adharsh M

Reputation: 3822

React Native - react-hook-form and typescript usage

I wanted to write a generic Input component in react native with typescript for react-hook-form library.

type InputTextProps = {
    name: any,
    control: any
}

const InputText: FC<InputTextProps> = ({name, control, ...props}) => {
    const {field} = useController({
        name,
        defaultValue: '',
        control
    })
    return (
        <TextInput 
            value={field.value}
            onChangeText={field.onChange}
            {...props}
        />
    )
}

In the above code, what should i use in InputTextProps ? I also want to extend TextInput's Props.

PS: Is using typescript in react native convenient ? I find is very much to be written especially for react navigation etc...

Upvotes: 1

Views: 2557

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

From what I understand, you want to have an exact type for name and control with other props in InputTextProps.

To do so, you can use UseControllerProps, it includes name and control property:

import { UseControllerProps, useController } from "react-hook-form";

type InputTextProps = {
  // other custom props 
} & UseControllerProps;

UseControllerProps in controller.d.ts

export declare type UseControllerProps<TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>> = {
    name: TName;
    rules?: Omit<RegisterOptions<TFieldValues, TName>, 'valueAsNumber' | 'valueAsDate' | 'setValueAs'>;
    shouldUnregister?: boolean;
    defaultValue?: UnpackNestedValue<FieldPathValue<TFieldValues, TName>>;
    control?: Control<TFieldValues>;
};

Upvotes: 2

Related Questions