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.
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}
/>
)}
/>
}
/>
);
};
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} /> }
/>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With