Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncontrolled Input to Controlled Input Warning in React Hook Form and Material UI's TextField

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!

like image 727
Lex Arisa Avatar asked Dec 06 '25 09:12

Lex Arisa


1 Answers

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: ''}
like image 120
sirius9515 Avatar answered Dec 07 '25 23:12

sirius9515



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!