💈 useFieldArray (#768)
- Custom hook for working with Field Arrays (dynamic inputs).
function Test() {
const { control, register } = useForm();
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
{
control, // control props comes from useForm (optional: if you are using FormContext)
name: "test" // unique name for your Field Array
}
);
return (
<>
{fields.map((field, index) => {
return (
<div key={field.id}> {/* important: using id from to track item added or removed */}
<input name={`test[${index}}]`} ref={register} />
</div>
);
})}
</>
);
}
Name | Type | Description |
---|---|---|
fields | object & { id: string } | This object is the source of truth to map and render inputs.Important: because each inputs can be uncontrolled, id is required with mapped components to help React identify which items have changed, are added, or are removed.eg: {fields.map(d => )} |
append | (obj: any) => void | Append input/inputs to the end of your fields |
prepend | (obj: any) => void | Prepend input/inputs to the start of your fields |
insert | (index: number, value: any) => void | Insert input/inputs at particular position. |
swap | (from: number, to: number) => void | Swap input/inputs position. |
move | (from: number, to: number) => void | Move input/inputs to another position.Note: difference between move and swap, keep calling move will push input/inputs in a circle, while swap only change two input/inputs' position. |
remove | (index?: number) => void | Remove input/inputs at particular position, or remove all when no index is provided. |