Replies: 1 comment
-
Here's a sandbox with an example of how to deal with nested field arrays. Nested field arrays are a bit more involved with how field arrays are treated in RHF, but the main rule of thumb is: make sure it's not a flat array if you need to Sandbox code for reference: import { useForm, useFieldArray } from "react-hook-form";
import type { UseFormRegister, Control, DefaultValues } from "react-hook-form";
type Option = {
value: string;
};
type Field = {
props: Array<Option>;
options: Array<string>;
};
type FormValues = {
fields: Array<Field>;
};
type NestedFieldArrayProps = {
control: Control<FormValues>;
register: UseFormRegister<FormValues>;
parentFieldIndex: number;
};
function NestedFieldArray({
control,
register,
parentFieldIndex
}: NestedFieldArrayProps) {
const { fields, append, remove } = useFieldArray({
control,
name: `fields.${parentFieldIndex}.props`
});
return (
<fieldset>
<legend>Nested field array</legend>
{fields.map((field, index) => (
<fieldset key={field.id}>
<legend>Prop #{index}</legend>
<label>Value:</label>
<input
{...register(`fields.${parentFieldIndex}.props.${index}.value`)}
/>
<button type="button" onClick={() => remove(index)}>
Remove (<i>Nested</i>)
</button>
</fieldset>
))}
<button
type="button"
onClick={() =>
append({
value: ""
})
}
>
Append (<i>Nested</i>)
</button>
</fieldset>
);
}
const defaultValues: DefaultValues<FormValues> = {
fields: [
{
props: [{ value: "Some value" }],
options: [""]
}
]
};
export default function App() {
const { control, handleSubmit, register } = useForm<FormValues>({
defaultValues
});
const { fields, append, remove } = useFieldArray({ control, name: "fields" });
return (
<form onSubmit={handleSubmit(console.info)}>
<fieldset>
<legend>Parent field array</legend>
{fields.map((field, index) => (
<fieldset key={field.id}>
<legend>Field #{index}</legend>
<label>Options</label>
<select {...register(`fields.${index}.options`)} multiple>
<option value="" disabled>
Select an option
</option>
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
<NestedFieldArray
control={control}
register={register}
parentFieldIndex={index}
/>
<button type="button" onClick={() => remove(index)}>
Remove (<i>Parent</i>)
</button>
</fieldset>
))}
<button
type="button"
onClick={() =>
append({
props: [{ value: "" }],
options: [""]
})
}
>
Append (<i>Parent</i>)
</button>
</fieldset>
<button>Submit</button>
</form>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am facing a situation where I need to add another array of fields inside an array of fields. inside that double nested array, I want to use the
append
,remove
, etc methods. is there any workaround for this with the current api?Beta Was this translation helpful? Give feedback.
All reactions