FieldArray React-Hook-Form
Unanswered
Ojos Azules posted this in #help-forum
Ojos AzulesOP
This is my ServiceSchema:
I want to create services with fieldarray and every time that i click "Add service" give me two fields to fill out. One for translation name and one for language.
This is my source code(form):
export const ServiceSchema = z.object({
translation: z.object({ name: z.string(), language: z.string() }).array()
})I want to create services with fieldarray and every time that i click "Add service" give me two fields to fill out. One for translation name and one for language.
This is my source code(form):
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-8 w-full"
>
<div className="grid grid-cols-3 w-full gap-8">
<div className="flex flex-col space-y-4">
{fields.map((field, index) => (
<FormField
key={field.id}
control={form.control}
name={`translation.${index}.name`}
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input
disabled={isPending}
placeholder="Service name"
{...field}
/>
</FormControl>
<FormMessage className="pt-2" />
</FormItem>
)}
/>
))}
<Button type="button" variant={"outline"} size={"sm"} className="mt-2" onClick={() => append({ language: "", name: "" })}>Add Service</Button>
</div>
</div>
<Button disabled={isPending} className="ml-auto" type="submit">
{action}
</Button>
</form>
</Form>interface ServiceFormProps {
initialData: ServiceTranslations | null;
}
export const ServiceForm = ({
initialData,
}: ServiceFormProps) => {
const router = useRouter();
const params = useParams();
const [error, setError] = useState<string | undefined>("");
const [isPending, startTransition] = useTransition();
const title = initialData ? "Edit service" : "Create service";
const description = initialData ? "Edit a service" : "Add a new service";
const action = initialData ? "Save changes" : "Create";
const form = useForm<z.infer<typeof ServiceSchema>>({
resolver: zodResolver(ServiceSchema),
defaultValues:
initialData ? {
...initialData
} : {
translation: "",
},
mode: "onChange"
});
const { fields, append } = useFieldArray({
name: "translation",
control: form.control,
})17 Replies
what's the issue then?
Ojos AzulesOP
i get only one field
for the translation name
ofcourse, you haven't added the formfield for language
you will get the input for only name
Ojos AzulesOP
🤔
did I get it wrong?
Ojos AzulesOP
Look
I want to create a single field with two inputs where the translation product and language are interrelated and stored together.
Ojos AzulesOP
ik lmao
Ojos AzulesOP
but i dont how i can achieve that
I get it
Ojos AzulesOP
Yeah i know its for someone that didnt understand it
well, you've already added the service name input, add the translation too