Skip to content

Instantly share code, notes, and snippets.

@bekzodnj
Last active January 22, 2023 12:20
Show Gist options
  • Save bekzodnj/ab0ecd06080ca3bd94a41de5642a4f7a to your computer and use it in GitHub Desktop.
Save bekzodnj/ab0ecd06080ca3bd94a41de5642a4f7a to your computer and use it in GitHub Desktop.
React Hook Form's `useFieldArray` hook. Examples of append, prepend, insert (with focus options). CodeSandbox: https://codesandbox.io/s/react-hook-form-focus-options-fn6fqq
// CodeSandbox link: https://codesandbox.io/s/react-hook-form-focus-options-fn6fqq
export default function App() {
const { register, control } = useForm<{
test: { value: string }[];
}>({
defaultValues: {
test: [{ value: "1" }, { value: "2" }]
}
});
const { fields, prepend, append, insert } = useFieldArray({
name: "test",
control
});
// append, prepend, insert options (obj: object | object[], focusOptions) => void
// type focusOptions = {
// shouldFocus?: boolean;
// focusIndex?: number;
// focusName?: string;
// };
return (
<form>
{fields.map((field, i) => (
<input key={field.id} {...register(`test.${i}.value` as const)} />
))}
<button
type="button"
onClick={() => prepend({ value: "prepended value" }, { focusIndex: 0 })}
>
prepend
</button>
<button
type="button"
onClick={() =>
append({ value: "appended value" }, { focusName: "test.1.value" })
}
>
append
</button>
<button
type="button"
onClick={() =>
insert(1, { value: "inserted value" }, { shouldFocus: false })
}
>
insert
</button>
</form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment