The problem is that my current implementation of the custom error component is using type casting which I would like to get rid of.

Here is what I tried. I have following form values:

type Item = {
  type: string;
  code: string;
  color?: string;
  value: number;
}
type MyFormValues = { items: Item[] }

From react-hook-form I receive e.g. following errors for items:

"items": [
  {
    "type": {
      "message": "validation_message_required_value",
      ...
    },
    "value": {
      "message": "validation_message_required_value",
      ...
    },
  }
]

And then I want to display all the errors for each item within one component. So in my case there are four fields next to each other and below them there would be the two error messages like this:

Type: "Field is required."
Value: "Field is required."

Currently I have this implementation:

import React from 'react';
import { FieldError, FieldErrorsImpl, Merge } from 'react-hook-form';
import { FieldValues } from 'react-hook-form/dist/types';

type ItemErrorProps<T extends FieldValues> = {
  error?: Merge<FieldError, FieldErrorsImpl<T>>;
};

const CustomFieldError = <T extends FieldValues>({
  error,
}: ItemErrorProps<T>) => {
  if (!error) {
    return null;
  }

  return (
    <>
      {Object.keys(error).map(fieldErrorKey => {
        const fieldError = (error[fieldErrorKey] ?? {}) as FieldError;
        const message = fieldError?.message;
        const messageKey = ['form_field', fieldErrorKey]
          .filter(x => x)
          .join('_');

        return (
          // not included in this example to keep it short
          <Message 
            key={fieldErrorKey}
            messageKey={messageKey}
            message={message}
          />
        );
      })}
    </>
  );
};

It works but it uses a type casting as FieldError. Is it possible to make it work without the type casting and also for items with other properties?

0

There are 0 best solutions below