error-message icon indicating copy to clipboard operation
error-message copied to clipboard

error message doesn't seems to work in usefieldarray

Open Bat-m opened this issue 3 years ago • 3 comments

the error dont appear in error message not sure if this is an issue but cant figure out an other way

const { fields } = useFieldArray({
    name: nameForm,
    ...methods.control
  });

fields.map((field: FieldValues, index: number) => {
            const id = '${nameForm}.${index}.checkbox'

            return (
                <input
                  {...methods.register(id, { required: required })}
                />
              </div>
            );
          })

<ErrorMessage
        errors={errors}
        name={nameForm}
        render={({ message }) => {
          return <div className="text-red-500 text-sm">{message}</div>
        }}
      />
Capture d’écran 2022-02-09 à 10 29 43

Bat-m avatar Feb 09 '22 09:02 Bat-m

I got it working by doing this:

 <ErrorMessage
        errors={methods.formState.errors}
        name={`${name}.root`} <-- This is important
        render={({ message, messages }) => {
          return (
            <span >
              {message}
            </span>
          );
        }}
      />

dd8888 avatar Jan 31 '23 12:01 dd8888

has anyone got this fixed? above solution doesn't work for me.

simonpeters avatar Apr 21 '23 15:04 simonpeters

For my case, yup resolver was causing the issue. (I was using Custom Hook with Resolver Shown in this docs )

To address the problem, I switched to using the @hookform/resolvers package.

However, I also discovered that using square brackets instead of a dotted name can resolve the issue.

For example, instead of test.${index}.lasttname, you can use test[${index}].lastName when defining the name property for a Controller component. This may be a simpler solution for some cases.

This works because the square brackets align with the name that Yup uses.

Hope it helps someone

iamjaydev avatar Apr 29 '23 12:04 iamjaydev