4

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?

3 Answers 3

3

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

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

Comments

1

Ok, I found answer myself. I should use this form:

{errors['xxx.yyy'] && This field is required}

Then everything works :-)

Comments

1

you don't want to spend your coding time. you can use @hookform/error-message instead of code manually. it's very easy. it'll manage those errors. just pass the errors object given by react-hook-form and pass the property name that you want to display the error message.

<ErrorMessage errors={errors} name="xxx.yyy" message="This is required" /> 

OR

if you want to customize your message as you want, you can render as you want like below. think that you want to bold and show invalid with red custom css class. then you can render as you want.

<ErrorMessage render={({message}) => <div className="invalid-feedback d-block"><b> {message} </b></div>} errors={errors} name="xxx.yyy"/>

NPM https://www.npmjs.com/package/@hookform/error-message

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.