import { type FieldPath, type FieldValues, useFieldArray, useFormContext, } from "react-hook-form"; import { FormMessage } from "~/components/FormMessage"; import { Label } from "~/components/Label"; import { AddFieldButton } from "./AddFieldButton"; import { RemoveFieldButton } from "./RemoveFieldButton"; export function TextArrayFormField({ label, name, bottomText, /** If "plain", value in the text array is a plain string. If "object" then an object containing the text under "value" key */ format = "plain", }: { label: string; name: FieldPath; bottomText?: string; format?: "plain" | "object"; }) { const { register, formState: { errors }, clearErrors, } = useFormContext(); const { fields, append, remove } = useFieldArray({ name, }); const rootError = errors[name]?.root; return (
{fields.map((field, index) => { // @ts-expect-error const error = errors[name]?.[index]?.value; return (
{ remove(index); clearErrors(`${name}.root`); }} />
{error && ( {error.message as string} )}
); })} append(format === "plain" ? "" : { value: "" })} /> {rootError && ( {rootError.message as string} )} {bottomText && !rootError ? ( {bottomText} ) : null}
); }