1

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?

2
  • Why not pass UseFormRegisterReturn instead of UseFormRegister? This lets you call register from the outside and you get the type-safety. Commented Mar 8, 2023 at 9:29
  • You don't need to pass register at all - it's passed in ref. See answer by @Joris. Should be accepted - works as a charm Commented Oct 8, 2023 at 3:16

1 Answer 1

7

You've to pass the ref and below is one of the ways to achieve that

export interface TextFieldProps extends React.PropsWithoutRef<JSX.IntrinsicElements["input"]> {
    error: string | undefined;
    label: string;
}

const TextField = forwardRef<HTMLInputElement, TextFieldProps>(({error,label,...props}, ref) => {
    return (
      <>
        <input className="border" {...props} ref={ref}></input>
        {error}
      </>
    )
  });

export default TextField

You're to be able to use it like:

<TextField {...register('username')} label="Username label" error={formState.errors.username.message}/>
Sign up to request clarification or add additional context in comments.

3 Comments

Missing an open bracket on the forwardRef, should be: ... LabeledTextFieldProps>(({ ...
Why not pass UseFormRegisterReturn instead of UseFormRegister? This allows you to call register from the outside and you get the type-safety.
This should be an accepted answer with extra bracket per above. Here's the reference from React Docs: react.dev/reference/react/forwardRef

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.