Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add errors when using useFieldArray with React Hook Form

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?

like image 998
user8006446 Avatar asked May 11 '26 08:05

user8006446


1 Answers

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

like image 77
knoefel Avatar answered May 12 '26 23:05

knoefel



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!