radix-ui / primitives

Radix Primitives is an open-source UI component library for building high-quality, accessible design systems and web apps. Maintained by @workos.
https://radix-ui.com/primitives
MIT License
15.54k stars 795 forks source link

Make radix checkbox work with RHF register #2525

Open norman-ags opened 10 months ago

norman-ags commented 10 months ago

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)

<CheckboxPrimitive.Root {...register("accepted")} />

Saw this issue in github: https://github.com/radix-ui/primitives/issues/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 have checked property.

const ref = useRef();

console.log(ref.current.checked) // true or false

<CheckboxPrimitive.Root ref={ref} />

This is just my opinion and if radix team think this is also correct, I'm happy to help/do a PR for this.

ctjhoa commented 8 months ago

I completely agree on this and for the record the issue is not limited to RHF. @tanstack/table is also impacted via RowSelection api where it expects something like

onChange={table.getToggleAllRowsSelectedHandler()}

With Radix, you cannot use this method because onChange is never triggered. You also cannot use onCheckedChange={table.getToggleAllRowsSelectedHandler()} because getToggleAllRowsSelectedHandler expect an event.

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

source: https://github.com/TanStack/table/blob/4e2dd61e620fd4b7114f8d1028c3f36e228993a3/packages/table-core/src/features/RowSelection.ts#L457

paolostyle commented 3 months ago

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.