'React-Hook Form: Cannot read properties of undefined (reading 'field')
My form is a nested one and if I'll only submit one product, there are no errors, But If I'll click Add More Product and click the button to add more colors this is the error that I'm getting:
Cannot read properties of undefined (reading 'field')
This is where it pointed out:
<input
36 | name={`test[${nestIndex}].nestedArray[${k}].color`}
37 | ref={register({ required: true })}
> 38 | defaultValue={item.field}
| ^
39 | style={{ marginRight: "25px" }}
40 | />
and here:
return (
19 | <div>
> 20 | {fields.map((item, k) => {
| ^
21 | return (
22 | <div key={item.id} style={{ marginLeft: 20 }}>
23 | <label>{k + 1}</label>
Adding more products, and adding more colors will make these errors appear
This is what the form looks like:
Codesandbox link: https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js
The error is in the fieldArray.js:
i
mport React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";
let renderCount = 0;
export default function Fields({ control, register, setValue, getValues }) {
const { fields, append, remove, prepends } = useFieldArray({
control,
name: "test"
});
renderCount++;
return (
<>
<ul>
{fields.map((item, index) => {
return (
<li key={item.id}>
{/* <select
ref={register()}
name={`test[${index}].name`}
defaultValue={item.name}
>
<option value="">Select</option>
<option value="10">ItemA</option>
<option value="20">ItemB</option>
</select> */}
{/* {index + 1} to show the qty */}
<TextField
name={`test[${index}].nestedArray[${index}].product`}
inputRef={register({ required: true })}
defaultValue={item.name}
/>
<button type="button" onClick={() => remove(index)}>
Delete
</button>
<NestedArray nestIndex={index} {...{ control, register }} />
</li>
);
})}
</ul>
<section>
<button
type="button"
onClick={() => {
append({ name: "append" });
}}
>
Add product
</button>
</section>
<span className="counter">Render Count: {renderCount}</span>
</>
);
}
How can I fix this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

