2

I'm having problems with validation errors using the new react-hook-form version 7 and was wondering if anyone can help (see example linked below).

https://codesandbox.io/s/react-hook-form-adapting-existing-form-forked-n3sis?file=/src/index.js

This all used to work until I updated from v6 to v7. I changed the way register was used, i.e. {...register('name', {required: 'Add this'})} instead of ref={register({required: 'Add this'})} and have updated getting the errors from formState now, i.e. const { formState: { errors }} = useForm(); instead of const { errors } = useForm();.

I'm pretty sure it's got something to do with me using a controlled component rather than just a native html <input /> but can't quite seem to figure it out.

Any help would be hugely appreciated. Thanks.

2 Answers 2

1

You just forgot to pass down props and ref to the input component.

const Input = React.forwardRef(
  ({ error, id, label, required, ...props }, ref) => {
    return (
      <>
        <label htmlFor={id}>{label}</label>
        <input id={id} required={required} {...props} ref={ref} />
        <span style={{ color: "red" }}>{error}</span>
      </>
    );
  }
);

Here is your codesandbox working: https://codesandbox.io/s/react-hook-form-adapting-existing-form-forked-dpxie?file=/src/index.js

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, glad it was something simple. I really like the simplicity of react-hook-form and was hoping it wasn't that the version bump had changed something drastically and made life more complicated.
Which additional props does it actually require as in this example we're just spreading all props, where as in my team world example I'd rather be in a little more control as to what can be passed through, i.e. I wouldn't want className being passed and added and overriding existing defined styles.
1

I wasted around two days just to find out that I was the one who caused the problem.

I disabled submit button if the formState.isValid was false. But the default useForm validation mode is onSubmit. In this mode errors only show up when you submit the form and it was impossible because I disabled the button.

mode change to onBlur or onChange solved the problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.