Make radix checkbox work with RHF register #3919
Replies: 4 comments
-
|
I completely agree on this and for the record the issue is not limited to RHF. onChange={table.getToggleAllRowsSelectedHandler()}With Radix, you cannot use this method because The workaround is to use something like onCheckedChange={(checked) => {
if (checked === 'indeterminate') {
return
}
table.toggleAllRowsSelected(checked)
}}This is very complicated / weird for something like a checkbox, where you expect to behave like native HTML |
Beta Was this translation helpful? Give feedback.
-
|
Bumping this as it's a big pain point for me as well. Also willing to contribute if there's an interest from the maintainers. |
Beta Was this translation helpful? Give feedback.
-
|
+100 for that. We need |
Beta Was this translation helpful? Give feedback.
-
|
The core reason Radix’s React Hook Form’s here's a workaround that allows you to use Radix ui Checkbox with RHF: // example of RHF, you need to pull the setValue method
const { register, handleSubmit, setValue, formState: { errors, isSubmitting } } = useForm<AuthSchema>();
// this is a method that will be passed to onCheckChange of Radix ui Checkbox, it will allow us to set the value of RHF checkbox input
const setCheckBoxValue = (checked: boolean | "indeterminate") => {
setValue("accepted", Boolean(checked));
};
// create a fake input which is hidden (display: none), but use it to track the checked status of Radix ui Checkbox
<input type="checkbox" {...register("accepted")} className="hidden" />
// pass the setCheckBoxValue to onCheckedChange to keep RHF checkbox field updated
<CheckboxPrimitive.Root onCheckedChange={setCheckBoxValue} className="mr-2" />Instead of relying on register() hooking directly into the Radix component, this:
This pattern works because:
check out this to see the official documentation of |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Overview
I noticed radix-checkbox component doesn't work with RHF register. It doesn't work because it's expecting ref.current.checked (just like a native HTML input)
Saw this issue in github: #734
I think using
onCheckedChange={field.onChange}should be a secondary option. IMO, a "CustomCheckbox" should be close to native HTML as possible. With that said I think the ref should havecheckedproperty.This is just my opinion and if radix team think this is also correct, I'm happy to help/do a PR for this.
Beta Was this translation helpful? Give feedback.
All reactions