9

How would you go about dynamically adding custom error messages to inputs that are generated with useFieldArray?

Very simple codesandbox here - https://codesandbox.io/s/romantic-dubinsky-xd6f7?file=/src/App.js

Usually I would write something like {errors.name && <p>This can't be empty</p>} however with useFieldArray the names of the inputs are dynamically generated. I've tried something like {errors.items.index.name && <p>This can't be empty</p>} but that doesn't work.

Any suggestions?

1
  • This bracket syntax is so confusing because it’s not mentioned on their website and it doesn’t match the field name i had the same problem with seterror Commented Jan 7, 2022 at 11:28

2 Answers 2

20

You were very close, but you need to use the bracket syntax (and also optional chaining to check if the path is available/valid):

{errors.items?.[index]?.name && <p>This can't be empty</p>}

Edit React Hook Form - FieldsArray - Display Error

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

Comments

1

is there a way to show only on blur? it looks like both the field is touched right away when you use append, and the error is there right away, vs the field that is already there the error shows onBlur by default.

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.