Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material-UI Checkbox is not reset while using react-hook-form reset function

I'm using

"react-hook-form": "7.9.0",

And

"@material-ui/core": "4.11.4",.

I'm trying to reset some checkbox manually by clicking on regular button and using the reset (react-hook-form reset) method of react-hook-form.

For some reason I can see in react dev tools that the "checked" prop is changing to false but the SwitchBase (v icon) is still on.

You can see example: Over here

Thank you for your time.

like image 247
Netanel Vaknin Avatar asked Sep 12 '25 01:09

Netanel Vaknin


2 Answers

The MUI <Checkbox /> component has a slighty different interface for setting a value. The RHF value has to be set with checked prop.

One important note: you have to set the value with checked={!!value} to avoid a warning about changing a component from uncontrolled to controlled in case that your defaultValue for someCheckbox is initially undefined.

export const Checkbox = ({
  name,
  label,
  control,
  labelPlacement,
  disabled,
  className
}) => {
  return (
    <FormControlLabel
      label={label}
      disabled={disabled}
      labelPlacement={labelPlacement}
      className={className}
      control={
        <Controller
          name={name}
          control={control}
          rules={{ required: true }}
          render={({ field: { value, ...field } }) => (
            <MuiCheckbox
              {...field}
              checked={!!value}
            />
          )}
        />
      }
    />
  );
};

Edit Issue with reseting Material UI Checkbox using react-hook-form (forked)

like image 182
knoefel Avatar answered Sep 13 '25 15:09

knoefel


The controller hook uses value (which is true/false) and not checked (which is what Checkbox of Material-UI expects) in order to set the check-status of the checkbox.

In order to fix your issue you can take the value from the field (inside the render property of the Controller) and set it to the checked property of the Checkbox:

  control={
    <Controller
      name={name}
      control={control}
      rules={{ required: true }}
      render={({ field }) => <MuiCheckbox {...field} checked={field['value'] ?? false} /> }
    />
  }
like image 43
Dekel Avatar answered Sep 13 '25 14:09

Dekel