1

I'm using React Hook Form. I have a checkbox wrapped in Controller.

  1. First problem is that onChange event always gives undefined
  2. Second problem - before the first appeared (unfortunately I don't know after which change) it managed to work but I didn't know how to get current form state - it was updated only after resetting or submitting the form. As you can see I have added a validation rule to the checkbox. I need to enable submit button based on that checkbox so I need to have a current formState immediately.
<Controller
                        render={({ field: { onChange, value } }) => (
                            <Checkbox
                                // checked={value}
                                onChange={(e) => {
                                    console.log(e.value);
                                    onChange(e.value);
                                   // this print undefined                                
                                }}
                            >
                                Some text
                            </Checkbox>)}
                        control={control} // this changes nothing
                        defaultValue={false} // I've tried also with default values passed to the FormProvider
                        name='checkbox'
                        rules={{
                            validate: (value: boolean) => value
                        }} />
3
  • write e.target.checked like onChange={(e) => onChange(e.target.checked)} instead of e.value. (*looks like you are using MUI for the Checkbox) Commented May 15, 2023 at 14:46
  • I'm using something similar to MUI and I've checked that e.value is what I need. In other cases when I'm using this checkbox onChange={onChange} is working Commented May 15, 2023 at 16:23
  • can you put this in codesandbox? and share url. Commented May 17, 2023 at 6:13

1 Answer 1

0

I've figured out that problem is that this checkbox needs string as a value, not a boolean

    <Controller
                        control={control}
                        render={({ field }) => (
                            <Checkbox {...field}
                                checked={field.value}
                                value={field.value as unknown as string}
                            >Text
                            </Checkbox>)}
                        defaultValue={false}
                        name='checkbox'
                        rules={{
                            validate: (value: boolean) => value
                        }} />
Sign up to request clarification or add additional context in comments.

1 Comment

The value do not update of the checkbox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.