nick
nick

Reputation: 3259

Custom input component with React Hook Form 7

So I have this component:

const TextInput = ({ type = 'text', fullWidth = false, ...rest }) => {
  return (
    <input
      type={type}
      className={`text-input ${classNames([fullWidth, 'fullwidth'])}`}
      {...rest}
    />
  );
};

and then I have this code:

const { register } = useForm();

//then in the return
<TextInput type='email' fullWidth {...register('email')} />

And I'm getting this error:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

How can I solved this? From what I looked I have to pass refs to the input but I don't know how to do this..

Upvotes: 0

Views: 1937

Answers (2)

user3869304
user3869304

Reputation: 873

const TextInput = ({ register ,name,type = 'text', fullWidth = false, ...rest }) => {
  return (
    <input
      type={type}
      {...register(name)}
      className={`text-input ${classNames([fullWidth, 'fullwidth'])}`}
      {...rest}
    />
  );
};

And then you can do

const { register } = useForm();

//then in the return
<TextInput type='email' fullWidth register={register} />

Upvotes: 2

nick
nick

Reputation: 3259

Okay so what I needed to do is use forwardRef like this:

const TextInput = React.forwardRef(({ type = 'text', fullWidth = false, ...rest }, ref) => {
  return (
    <input
      type={type}
      className={`text-input ${classNames([fullWidth, 'fullwidth'])}`}
      {...rest}
    />
  );
});

Upvotes: 1

Related Questions