javascript - use react hook form with custom TextInput - Stack Overflow

I'm trying to use react hook form with custom TextInput. Before I was using materials input and ev

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 ponent:

          <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 ponent 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 ponents cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? How should that TextField ponent look to avoid that forwardRef warning?

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 ponent:

          <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 ponent 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 ponents cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? How should that TextField ponent look to avoid that forwardRef warning?

Share Improve this question asked Jul 28, 2021 at 18:06 Arek SzastArek Szast 2037 silver badges18 bronze badges 2
  • Why not pass UseFormRegisterReturn instead of UseFormRegister? This lets you call register from the outside and you get the type-safety. – Florian Walther 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 – lentyai Commented Oct 8, 2023 at 3:16
Add a ment  | 

1 Answer 1

Reset to default 6

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, LabeledTextFieldProps>({ errorm label, ...props }, ref) => {
    return (
      <>
        <input {...props} ref={ref}></input>
        {error}
      </>
    )
  });

You're to be able to use it like:

<TextField {...register('username')} label="Username label" error={formState.errors.username.message}/>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745574600a4633886.html

相关推荐

  • javascript - use react hook form with custom TextInput - Stack Overflow

    I'm trying to use react hook form with custom TextInput. Before I was using materials input and ev

    17小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信