'How to access the error message using yup and react-hook-form through formState?

I'm trying to display the error message I set using yup validation - my schema for displayName looks like this:

 displayName: yup.string().required("Please enter a username")

I'm using react-hook-form for my forms and my textfield goes something like this:

    <Controller
      render={({ field, formState }) => (
      <TextField
      {...field}
      label="display name"
      error={!!formState.errors?.displayName}
      helperText={!!formState.errors?.displayName ? formState.errors?.displayName.message : null}
      />
     )}
     name="displayName"
     control={control}
     defaultValue=""
    />

Unfortunately, my screen goes blank. I tried looking for the reason why it happened and apparently, it's because of formState.errors?.displayName.message but at the same time, it contains the error message for my field. Is there any way I can access it so I can use it for my helperText?



Solution 1:[1]

Is your TextField a component of MUI?
I tried to reproduce it with MUI + RHF + yup in the same way,

Is there any way I can access it so I can use it for my helperText?

It seems that the error is output to helperText without any problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rin