Home > other >  Custom input from react-form-hook not working
Custom input from react-form-hook not working

Time:08-30

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.

CodePudding user response:

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

  • Related