How to preserve hidden fields in react-hook-form fieldArray?

Viewed 7766

I'm trying to build list of forms based on array of objects, those objects have fields that should have the ability to be edited, and be rendered as inputs, and readonly fields that don't need to be rendered, for example id.

I do that by using useFieldArray hook. However, react hook seems to save only those fields that are registered as inputs, which results in my id field getting lost in submit handler.

How do I preserve my readonly fields?

Here's sandbox example, so you can get what I am talking about. I added id to default value and to value that gets appended. When you click submit id is no longer there.

1 Answers

Use <input type='hidden' /> for fields you don't want to display to user like user ID and register as normal. So in your code you should add another input for id like this:

<input type="hidden" {...register(`test[${index}].useId`)} />

This is just like when you set display: none, but the field value is still submitted.

Live Demo

Codesandbox Demo

Related