Skip to content

[bug]: Base-UI Checkbox/Switch components are not labeled correctly in forms #9249

@RawToast

Description

@RawToast

Describe the bug

The labels for switch/checkbox items do not target the switch/checkbox. Instead they target an invisible input, leading to poor accessibility. This does not occur on the forms shown in the base-ui documentation, which label the correct item.

Not only is this an accessibility bug, but it makes the components hard to test using React Testing Library/Playwright selectors. The expected behaviour would allow selecting using role and name e.g. .getByRole("switch", { name: "label text" }), similar to screenreader users; however, this will not work as the switch/checkbox will have no name. Attempting to select the input instead will also fail, as it is hidden.

Switching the components back to radix ui fixes the issue immediately.

Accessibility tree using base-ui:

Image

Accessibility tree using radix-ui:

Image

Issue can also be seen here: https://basecn.dev/docs/components/field

Affected component/components

Switch, Checkbox, Field

How to reproduce

Create a form using the new field, similar to the examples and include a switch or checkbox.
Inspect the form with the accessibility view.

See codesandbox: https://codesandbox.io/p/devbox/hghqmf

https://hghqmf-5173.csb.app/

My repository is private, but something like this (tanstack form)

 <FieldGroup>
              <form.Field
                name="showMistakes"
                children={(field) => (
                  <Field orientation="horizontal">
                    <FieldContent>
                      <FieldLabel htmlFor={field.name}>Show Mistakes</FieldLabel>
                      <FieldDescription>Display mistake counter in the status bar</FieldDescription>
                    </FieldContent>
                    <Switch
                      id={field.name}
                      name={field.name}
                      checked={field.state.value as boolean}
                      onCheckedChange={(checked) => field.handleChange(() => checked)}
                    />
                  </Field>
                )}
              />

Codesandbox/StackBlitz link

Hastily put together from a tailwind 3 template 😵‍💫

https://codesandbox.io/p/devbox/hghqmf

https://hghqmf-5173.csb.app/

Same issue:

Image

Logs

System Info

MacOS, Firefox, Chrome, Safari, BaseUI

Before submitting

  • I've made research efforts and searched the documentation
  • I've searched for existing issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions