Search code examples
reactjsformsshadcnui

How to work with Shadcn/ui error messages for an array of FormFields


I am working on a form that has 2 arrays of objects in it. They are working as expected, and I am now working on displaying the error messages for them. This is the code I have currently:

<div className="mb-10">
  <h2 className="mb-2 text-xl font-semibold">
    Can you list the key steps you need to take?
  </h2>
  <div className="flex flex-col gap-2">
    {stepFields.map((field, i) => (
      <FormField
        key={field.id}
        name={`steps[${i}].title`}
        render={() => (
          <FormItem>
            <div className="flex gap-2">
              <Button variant={"ghost"} onClick={() => removeStep(i)}>
                <LuTrash2 className="h-5 w-5" />
              </Button>
              <FormControl>
                <div className="flex w-full gap-2">
                  <Input
                    {...form.register(`steps.${i}.title`, {
                      required: true,
                    })}
                    placeholder={`Step ${i + 1}`}
                    className="w-full bg-zinc-50 p-2"
                  />
                  <Input
                    {...form.register(`steps.${i}.date`, {
                      required: true,
                    })}
                    type="date"
                  />
                </div>
              </FormControl>
            </div>
          </FormItem>
        )}
      />
    ))}
    <Button
      variant={"secondary"}
      className="border"
      onClick={() => addStep({ title: "", date: "" })}
      type="button"
    >
      Add step
    </Button>
  </div>
</div>;

Now I want to display my Zod validation error messages using the <FormMessage /> and <FormLabel /> components from Shadcn/ui. However, if I would place these in the array, they would appear several times...

Has anybody ever encountered this and found a way around it. Is it possible for example to attach a field manually to a FormLabel, or does it always have to be within a FormField > FormItem.

Fyi, shadcn/ui uses react-hook-form under the hood.


Solution

  • Incase you want to display error message below the first item than:

    { !i && <FormMessage /> }
    

    For below the last item:

    { i+1 == stepFields.length && <FormMessage /> }