最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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}/>
发布评论

评论列表(0)

  1. 暂无评论