How to pass variable in register of react-hook-form 7

Viewed 588

Since v 7, react-hook-forms have stopped using refs. I have been trying to make my form dynamic, taking field props from a json file, but the register of useForm gives me a type issue everytime.

const {register , and so on..}= useForm({defaultvalues : {A:a,B:b, and so on..}})
...
{fields.map(f,i)=>
<TextField id={f.id} ..and so on.. 
{...register(`${f.id}` as const)} //error
/>}

The error being :

type string is not assignable to parameter of type '"A"|"B"| and so on'. ts2345

f.id returns the same values they want over there, yet i cant solve this.

1 Answers

I had the same problem. Try building the same structure for your register name as in your object. For example if you have this object:

{
   "car":[
      {
         "seat0":"color"
      },
      {
         "seat1":"color"
      }
   ]
}

Then if you want to map trough this and build your table, just do something like this.

{ data.map((item, index) => { 
              return (<TextField id={index} ..and so on.. 
              {...register(`car.seat${index}.color`)} />);
          }) }
Related