1
votes

I can't set the value of a material-ui checkbox programmatically using react-hook-form reset method

Here there is an example of my code, as you can note, TextField works correctly, CheckBox doesn't!

https://codesandbox.io/s/cocky-shamir-8lqph?file=/src/App.js

1

1 Answers

0
votes

According to the controller example and the doc, you can use Controller from react-hook-form to change the value of material UI checkboxes properly. sandbox

first checkbox (without label) would be as below:

<Controller
          name="checkwithoutlabel"
          control={control}
          defaultValue={false}
          rules={{ required: true }}
          render={(props) => (
            <Checkbox
              onChange={(e) => props.onChange(e.target.checked)}
              checked={props.value}
            /> 
          )}
/>

And the FormControlLabel component should be written like:

<FormControlLabel
          control={
            <Controller
              name={"checkwithlabel"}
              control={control}
              defaultValue={false}
              render={(props) => (
                <Checkbox
                  {...props}
                  checked={props.value}
                  onChange={(e) => props.onChange(e.target.checked)}
                />
              )}
            />
          }
          label={"Checkbox with label"}
        />