Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors in react-hook-form

According to documentation of react-hook-form I can use name of input element like this "xxx.yyy" and this will result in my prepared data to be

{ xxx: { yyy: value }}

But when I try to use this feature with 'errors' I cannot use it. i.e. I cannot write below:

{errors.xxx.yyy && <span>This field is required</span>}

because I get "Cannot read property 'yyy' of undefined".

Documentation says that I should use this chaining operator, ?. , so I try it:

{errors?.xxx?.yyy && <span>This field is required</span>}

But nothing displays on the page if required input is omitted. I can see that the mechanism blocks form from being submitted until I write something in this field, that is OK, but why I don't get the error message on the page?

like image 459
YotKay Avatar asked Nov 06 '25 03:11

YotKay


1 Answers

it really depend which version you are using.

V3: flat error object

errors['xxx.yyyy']

V4: Nested errors object with better type support

errors?.xxx?.yyyy

we have also build a ErrorMessage component which you may find it useful.

https://react-hook-form.com/api#ErrorMessage

like image 196
Bill Avatar answered Nov 09 '25 01:11

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!