简体   繁体   中英

Custom input from react-form-hook not working

Following the example here I have a custom input component:

Input.tsx

import React from "react";

export default function Input({label, name, onChange, onBlur, ref}:any) {

    return (
        <>
        <label htmlFor={name}>{label}</label>
        <input
          name={name}
          placeholder="Jane"
          onChange={onChange}
          onBlur={onBlur}
          ref={ref}
        />
      </>
    );
}

An example of the usage:

import {useAuth} from '../components/AuthContextProvider'
import { useForm, SubmitHandler } from "react-hook-form";
import Input from '../components/Input'


function Subscriptions({ Component, pageProps }: any) {
  const { user  } = useAuth()
  const { register, handleSubmit, formState: { errors } } = useForm<Inputs>();

  const onSubmit: SubmitHandler<Inputs> = async data => {
    console.log(data, 'data sdfdsg')
  }


  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Input label="name" {...register('name')}/>
        <button type='submit'>Add kid</button>
      </form>
    </>
    )
}

export default Subscriptions

Here's my package version:

"react-hook-form": "^7.34.2"

Any ideas what I'm doing wrong here?

The custom input receives undefined but it works with normal <input /> tags.

I've used the example in a codesandbox and it threw errors about ref and it suggested using React.forwardRef , change your custom Input to this:

function Input({ label, name, onChange, onBlur }, ref) {
  return (
    <>
      <label htmlFor={name}>{label}</label>
      <input
        name={name}
        placeholder="Jane"
        onChange={onChange}
        onBlur={onBlur}
        ref={ref}
      />
    </>
  );
}

const MyInput = React.forwardRef(Input);

export default MyInput;

and by the way, ref is not part of props I don't know why the example has it like that, it's necessary to use forwardRef so it is passed as second argument.

you can see the full example in this codesandbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM