I'm trying to use react hook form with custom TextInput. Before I was using materials input and everything was working correctly. A found one way that I can achieve it but I'm not satisfied with that.
I'm using useForm hook
const {
register,
handleSubmit,
formState: { errors, isValid },
} = useForm<FormValues>({ resolver: yupResolver(schema), mode: "all" });
And my custom TextField (pretty simple because for now I want just to register it into form):
export interface TextFieldProps {
id: string;
error: string | undefined;
label: string;
register: UseFormRegister<any>
}
const TextField = ({ id, error, label, register }: TextFieldProps): JSX.Element => {
return <>
<input {...register(`${id}`)}></input>
{error}
</>
};
using that component:
<TextField
register={register}
id="username"
label="Username"
error={errors.username?.message}
/>
This code is working but I'm losing IMO very nice feature - checking the name that I passed to register function. For example I have some schema declared:
const schema = yup.object({
username: yup.string().required("Username is required"),
password: yup.string().required("Password is required"),
});
And If I try the code below. Typescript will say me that I don't have email field in my schema.
<input
{...register("email")}>
</input>
I'm still trying to modify TextInput component to be able to use it like:
<TextField
{...register("username")}
id="username"
label="Username"
error={errors.username?.message}
/>
but I'm still facing with warning Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
How should that TextField component look to avoid that forwardRef warning?
UseFormRegisterReturninstead ofUseFormRegister? This lets you callregisterfrom the outside and you get the type-safety.registerat all - it's passed inref. See answer by @Joris. Should be accepted - works as a charm