9

i'm trying to build a form using React Hook Form (version 7.6.6). I created a FormInput component as seen below:

const FormInput = ({ name, label }) => {
  const { control } = useFormContext();

   return (
    <Grid item xs={12} sm={6}>
      <Controller
        control={control}
        name={name}
        render={({ field }) => {
          return <TextField {...field} label={label} fullWidth required />;
        }}
      />
    </Grid>
  );

and i'm using it here:

<FormProvider {...methods}>
        <form onSubmit={handleSubmit((data) => console.log(data))}>
            <FormInput name="firstName" label="First Name" />
            <FormInput name="lastName" label="Last Name" />
            <FormInput name="address1" label="Address 1" />
            <FormInput name="email" label="Email" />
            <FormInput name="zip" label="ZIP code" />
       
         
          <Button
            type="submit"
            Continue to Payment
          </Button>
        </form>
</FormProvider>

However, i'm getting an error saying

Warning: A component is changing an uncontrolled input to be controlled...

I've already checked with React Hook Form documentation and cannot seem to find what's causing the warning. What am I doing wrong?

Thank you!

Lex Arisa
  • 148
  • 1
  • 8

1 Answers1

23

I think your problem is similar to this one.

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

It is not a problem related to the hook. In my view, if an input does have no value attribute or when value is given as undefined in the first place, it is considered as uncontrolled input. So I want to suggest 2 solutions.

1) Setting defaultValue

<Controller
    defaultValue = {''}
    ...
/>

2) Check context value
Check initial context value and update them like this.

data: {} => data: { field1: '', field2: ''}
Dharman
  • 30,962
  • 25
  • 85
  • 135
sirius9515
  • 309
  • 1
  • 8
  • You just saved me from a mental breakdown! Thank you so much. Setting the defaultValue on Controller solved this issue (I was seeing it in my Jest tests). – user.io Jan 19 '22 at 18:58
  • 7
    Setting default value is no practical solution. What if I have tens of fields? Why should I set everyone's default value. And if I have an edit (not create) form I will need to test against the existing form values like so -> defaultValue={incomingData[fieldName] || ''}. There is no point in that. Hook forms should provide null default value for every field that the user does not provide default value – Thanasis Ioannidis Jul 18 '22 at 09:12
  • They don't explicitly mention it, but [this does seem to be "officially implied" way to go about things here](https://react-hook-form.com/advanced-usage#ControlledmixedwithUncontrolledComponents) (note the specified default value) – Mattwmaster58 Aug 14 '23 at 04:24