How to fix React hook form Controller defaultValue type warning in typescript?

Viewed 258

I am using react-hook-form with react-select using typescript.

     <Controller
              name="year"
              control={control}
              defaultValue={yearOptions[0]}
              render={({ field }) => (
                <SingleSelect
                  label="Select Release Year"
                  styles={noDotColourStyles}
                  data={yearOptions}
                  field={field}
                  errorMessage={errors.year?.message}
                />
              )}
            />

Here is the SingleSelect.tsx component.


export const SingleSelect: FunctionComponent<SingleSelectProps> = (props: SingleSelectProps) => {
  const { label, data, styles, field, errorMessage } = props;
  return (
    <FieldWrapper label={label} errorMessage={errorMessage}>
      <Select
        defaultValue={data[0]}
        options={data}
        styles={styles}
        instanceId={label}
        id={label}
        {...field}
        aria-label={label}
        aria-labelledby={label}
      />
    </FieldWrapper>
  );
};

I am trying to display defaultValues and everything works as expected. But there is a type error on the

     <Controller
              name="year"
              control={control}
              defaultValue={yearOptions[0]}

typeError

Here is the shape of DataOption:

export interface DataOption {
  readonly value: string;
  readonly label: string;
  readonly color: string;
}

And here is the example of yearOptions


export const yearOptions: readonly DataOption[] = [
  { value: '2022', label: '2022', color: '#00B8D9' },
  { value: '2021', label: '2021', color: '#0052CC' },
  { value: '2020', label: '2020', color: '#5243AA' },
  { value: '2019', label: '2019', color: '#FF5630' },
]

Here is the data after I submit the form and the UI.

UI:

UI

console data:

console data BUT If I change the values from defaultValue={yearOptions[0]} to defaultValue={yearOptions[0].value} the error goes way.

onSubmitting the form I get this yup error.

year must be a `object` type, but the final value was: `null` (cast from the value `"2022"`). If "null" is intended as an empty value be sure to mark the schema as `.nullable()`

So, I have changed the yup schema to use nullable from


    year: yup
      .object()
      .shape({
        value: yup.string(),
        label: yup.string(),
        color: yup.string(),
      })
      .required('Year is required'),

to


    year: yup
      .object()
      .shape({
        value: yup.string(),
        label: yup.string(),
        color: yup.string(),
      })
      .nullable()
      .required('Year is required'),

So now the yup nullable error is gone, but it does not take the default values. no default values

How to make react-hook-form accept defaultValues of custom types?

0 Answers
Related