i am using react hook form to build demo application.I am using usefieldarray
to append rows.
I already defined interface
export interface InitiateHoldModel {
checked: boolean | null;
containers: Array<ContainerOnHold> | null;
}
export interface ContainerOnHold {
checked: boolean;
number: string;
size: string;
}
Here is my code https://codesandbox.io/s/priceless-kowalevski-c0qjmh?file=/src/ReleaseFields.tsx:0-805
import { HookCheckBox, useHookFormContext } from "mui-react-hook-form-plus";
import { useFieldArray } from "react-hook-form";
export default function ReleaseFields(): JSX.Element {
const { registerState, control } = useHookFormContext();
const prependKey = "containers";
const { fields } = useFieldArray({
control,
name: prependKey
});
return (
<>
<HookCheckBox {...registerState("checked")} />
<label>B344332</label>
{fields.length > 0 && (
<ul>
{fields.map((item, index) => (
<li key={index}>
<HookCheckBox
{...registerState(`${prependKey}[${index}].checked`)}
/>
{item.number}
{item.size}
</li>
))}
</ul>
)}
</>
);
}
CodePudding user response:
Use getValues
to display
export default function ReleaseFields(): JSX.Element {
const { registerState, control, getValues } = useHookFormContext();
const prependKey = "containers";
const { fields } = useFieldArray({
control,
name: prependKey
});
return (
<>
{fields.length > 0 && (
<ul>
{fields.map((item, index) => (
<li key={item.id}> // use item.id as key - it's important
<HookCheckBox
control={control}
{...registerState(`${prependKey}[${index}].checked`)}
/>
<span>{getValues(`${prependKey}[${index}].number`)}</span>
<span>{getValues(`${prependKey}[${index}].size`)}</span>
</li>
))}
</ul>
)}
</>
);
}
Also cleaned up your App.tsx