How do I use useFieldArray with a generic Control Type? #11708
-
I am trying to build a custom component that takes a generic control from a useForm. In this component i want to use useFieldArray to add a variable amount of input fields. When I set my generic component up to take any fields additionally to the ones I care about, I always get a type error in various places along the lines of:
I want to do this, so that I can reuse my custom components with different forms that all include my relevant fields. Check my mini example here: https://codesandbox.io/p/sandbox/bold-hooks-pwq6k7?file=%2Fsrc%2FApp.tsx |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I grabbed the hint from here. import React from 'react';
import { Control, useFieldArray, useForm } from "react-hook-form";
type GenericFormData = {
theFieldICareAbout: { name: string }[];
};
type FirstFormValues = {
task: string;
} & GenericFormData;
type SecondFormValues = GenericFormData;
type GenericComponentProps<TFormValues> = {
control: TFormValues extends GenericFormData ? Control<TFormValues> : never;
};
function GenericComponent<TFormValues extends GenericFormData>({
control,
}: GenericComponentProps<TFormValues>) {
const { append } = useFieldArray({
control,
name: "theFieldICareAbout",
});
const onAppendQuestionGroup = () =>
append({
name: "",
});
return <div></div>;
}
export default function App() {
const { control } = useForm<FirstFormValues>();
const { control: secondFormControl } = useForm<SecondFormValues>();
return (
<div>
<GenericComponent control={control} />
<GenericComponent control={secondFormControl} />;
</div>
);
} |
Beta Was this translation helpful? Give feedback.
I grabbed the hint from here.
[playground]