Typescript: register type on custom input #3382
-
With a component that looks like this, is there a way to get the type props = {
label?: string
name: string
type: string
noMargin?: boolean
inline?: boolean
required?: boolean
register: any
error: Error
}
const Input: FC<props> = ({
label,
name,
type = 'text',
noMargin,
inline,
required,
register, // from react-hook-form
error, // error from react-hook-form
...props
}) => {
const hasError = error?.message?.length
return (
<InputView noMargin={noMargin} inline={inline} error={hasError}>
{label ? <InputLabel htmlFor={name} inline={inline} error={hasError} required={required}>{label}</InputLabel> : null}
<FormInput id={name} name={name} inline={inline} type={type} error={hasError} ref={register} {...props} />
{hasError ? <ErrorView inline={inline}>{error?.message}</ErrorView> : null}
</InputView>
)
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
yes you can: https://react-hook-form.com/ts#UseFormMethods |
Beta Was this translation helpful? Give feedback.
-
Hello @joaoreynolds , if you are calling register as a prop in a custom component or to use in some custom input field in Typescript, then you can use the below code. First of all import the UseFormRegister and FieldValues from 'react-hook-form'
After that, define the type of register as
and boom, you don't need to use 'any' type for register. |
Beta Was this translation helpful? Give feedback.
-
What happened we set our own interface as FieldValues export interface FormValues extends FieldValues {
firstName: string;
nickName: string;
familyName: string;
personalPhone: string;
personalEmail: string;
lastName: string;
}
const {
control,
register,
handleSubmit,
formState: { errors },
} = useForm<FormValues>({
defaultValues: {
firstName: '',
nickName: '',
familyName: '',
personalPhone: '',
personalEmail: '',
lastName: '',
},
resolver: valibotResolver(schema),
}); In this case we cannot use
is there any solution |
Beta Was this translation helpful? Give feedback.
Hello @joaoreynolds , if you are calling register as a prop in a custom component or to use in some custom input field in Typescript, then you can use the below code.
First of all import the UseFormRegister and FieldValues from 'react-hook-form'
import {UseFormRegister, FieldValues } from 'react-hook-form'
After that, define the type of register as
register: UseFormRegister<FieldValues>
and boom, you don't need to use 'any' type for register.