When to use it#
- Use a checkbox for one yes-or-no answer: a declaration, a consent, or a “select all” in a staff table.
- Write the label as a sentence that can be answered “yes”: “I confirm that the information is correct”.
- Not for several answers to one question: use a CheckboxGroup. Not for exactly one answer out of several, or for a question that needs both a yes and a no: use a RadioGroup.
- Not for an action or a setting that takes effect at once: use a Button, or a Switch for a saved setting.
Example#
import { Checkbox, Field } from '@kvirn-ui/react'
import { useCheckboxTexts } from './texts.ts'
export function DefaultCheckbox() {
const { texts } = useCheckboxTexts()
return (
<Field.Root>
<Checkbox name="newsletter" />
<Field.Label>{texts.newsletter}</Field.Label>
</Field.Root>
)
}Use cases#
A declaration that must be confirmed
A declaration or a consent is one box the user has to tick before sending. Mark the Field as required, so the label has no “(optional)” and a screen reader (software that reads the screen aloud) says the box is required. Check the answer when the user sends the form. Then set invalid and say what to do.
import { Button, Checkbox, Field } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { useCheckboxTexts } from './texts.ts'
export function Declaration() {
const { texts } = useCheckboxTexts()
const [checked, setChecked] = useState(false)
const [attempts, setAttempts] = useState(0)
const checkboxRef = useRef<HTMLInputElement>(null)
const isInvalid = attempts > 0 && !checked
// The Checkbox never moves focus: after a failed send, you move it to the box, so a screen
// reader reads the label, the state and the error together.
useEffect(() => {
if (attempts > 0) {
checkboxRef.current?.focus()
}
}, [attempts])
return (
<form
noValidate
onSubmit={(event) => {
// A real form sends the data from here.
event.preventDefault()
if (!checked) {
setAttempts((count) => count + 1)
}
}}
>
<Field.Root required invalid={isInvalid}>
<Checkbox
ref={checkboxRef}
name="declaration"
checked={checked}
onCheckedChange={setChecked}
/>
<Field.Label>{texts.declaration}</Field.Label>
<Field.ErrorMessage>{texts.declarationError}</Field.ErrorMessage>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
</form>
)
}Props in this example:
checkedon CheckboxonCheckedChangeon Checkbox
Warning: Don't forget
Set invalid and show the Field.ErrorMessage together, then move focus to the box after a failed send. An error is read only when its field gets focus, so without the move a screen reader user isn’t told what went wrong (3.3.1 Error Identification).
In a plain form, with no form logic
Without checked the browser keeps the state. A form submit sends the name and value of a ticked box, and nothing for an unticked one.
import { Button, Checkbox, Field } from '@kvirn-ui/react'
import { useState } from 'react'
import { useCheckboxTexts } from './texts.ts'
export function PlainForm() {
const { texts } = useCheckboxTexts()
const [sent, setSent] = useState<string | undefined>()
return (
<form
onSubmit={(event) => {
// A real form sends the data from here.
event.preventDefault()
const newsletter = new FormData(event.currentTarget).get('newsletter')
setSent(typeof newsletter === 'string' ? newsletter : texts.notChosen)
}}
>
<Field.Root>
<Checkbox name="newsletter" value="yes" />
<Field.Label>{texts.newsletter}</Field.Label>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
{sent === undefined ? null : (
<p>
{texts.sent} {sent}
</p>
)}
</form>
)
}Props in this example:
Information: Did you know?
defaultChecked starts a box ticked. Don’t use it for a consent: the GDPR says pre-ticked boxes don’t count as consent (recital 32).
An option with a short explanation
A consent often needs one more sentence. Put it in a Field.HelpText under the label: the screen reader reads it as the box’s description when the box gets focus.
We send at most one message a month. You can unsubscribe in every message.
import { Checkbox, Field } from '@kvirn-ui/react'
import { useCheckboxTexts } from './texts.ts'
export function WithHelpText() {
const { texts } = useCheckboxTexts()
return (
<Field.Root>
<Checkbox name="newsletter" />
<Field.Label>{texts.newsletter}</Field.Label>
<Field.HelpText>{texts.newsletterHint}</Field.HelpText>
</Field.Root>
)
}Information: Did you know?
A help text is plain text: no link, list or heading. A screen reader reads it as one flat string, so a link or list in it would lose its meaning.
Select all, with a mixed state
A “select all” box shows a mixed state while only some rows are chosen: not all, and not none. You set indeterminate from your data. The browser does not clear it when the user clicks, so your data must.
import { Checkbox, Field } from '@kvirn-ui/react'
import { useState } from 'react'
import { useCheckboxTexts } from './texts.ts'
export function SelectAll() {
const { texts } = useCheckboxTexts()
const rows = [texts.rowOne, texts.rowTwo, texts.rowThree]
const [selected, setSelected] = useState<readonly number[]>([0])
const allSelected = selected.length === rows.length
const someSelected = selected.length > 0 && !allSelected
return (
<div>
<Field.Root>
<Checkbox
checked={allSelected}
indeterminate={someSelected}
onCheckedChange={(checked) => setSelected(checked ? rows.map((_, index) => index) : [])}
/>
<Field.Label marker="none">{texts.selectAll}</Field.Label>
</Field.Root>
{rows.map((row, index) => (
<Field.Root key={row}>
<Checkbox
checked={selected.includes(index)}
onCheckedChange={(checked) =>
setSelected((current) =>
checked ? [...current, index] : current.filter((other) => other !== index),
)
}
/>
<Field.Label marker="none">{row}</Field.Label>
</Field.Root>
))}
</div>
)
}Props in this example:
checkedon Checkboxindeterminateon CheckboxonCheckedChangeon Checkbox
Warning: Don't forget
Give every row’s box its own visible label that tells the rows apart, such as the case number. Boxes that all read “Select” can’t be told apart (2.4.6 Headings and Labels; 4.1.2 Name, Role, Value).
Accessibility#
What it does for you#
- APG pattern: Checkbox. Dual-state and tri-state ("mixed") are both covered, with the native element:
<input type="checkbox">and itsindeterminateproperty. No ARIA is added. - Deviations: none from APG. Choices made: Field wiring, no form state, option labels have no optional marker.
- Native elements used:
<input type="checkbox">, named by a<label for>(Field.Label).
A Checkbox is one yes-or-no answer: a declaration, a consent, a "select all" in a staff table. It is a native input, so the browser supplies the role, the Space key, the label click and form submission. Checkbox adds the Field's wiring, the part class, indeterminate and data-state. It holds no form state: pass checked and onCheckedChange from your form logic, or defaultChecked and name for a plain form.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| Checkbox | <input type="checkbox"> → checkbox | Native checked. indeterminate is the DOM property, so assistive technology hears "mixed" (aria-checked is never written). id and aria-describedby (the option's help text, then the error) from the Field. aria-invalid="true" and aria-required="true" from the Field. Native disabled. data-state, data-invalid, data-required, data-disabled, data-focus-visible | Class kv-checkbox. Props: checked, defaultChecked, onCheckedChange(checked, { reason: 'input', event }), indeterminate, value, disabled, and every native input prop (name, form, onChange, ref). type is fixed. It must be a direct child of Field.Root, before the Field.Label |
| Field.Label | <label for>, the checkbox's name | The whole label is the click target (native) | In a standalone Field the label shows "(optional)" unless the Field is required or marker="none". In a group it shows nothing (checkbox-group.a11y.md) |
useCheckbox | the same attributes, for your own elements | inputProps, isIndeterminate, isInvalid, isRequired, isDisabled, isFocusVisible | Spread inputProps on your <input type="checkbox">. It includes a ref that sets the DOM indeterminate property |
Rules, tested in checkbox.test.tsx:
- A native checkbox.
<input type="checkbox">, classkv-checkbox, no ARIA role and noaria-checked(checkbox.test.tsx › renders a native <input type="checkbox">, outside a Field). - Named by its label. In a Field the label's
formatches the input'sid; the accessible name is the label text, with "(optional)" in a standalone, non-required Field (checkbox.test.tsx › the Field’s label is the name, and the description is the option’s help text). The help text is aField.HelpTextin the option's Field, outside the label: its description is its text content, so keep it short and plain. indeterminateis a DOM property set after render (it can't be set in markup): the checkbox exposes "mixed" anddata-state="indeterminate". The first server-rendered paint is unchecked. A click or Space toggles the underlyingcheckedstate and callsonCheckedChangewith it: withchecked={false}, as in the docs example, that istrue, so it checks the box. Whether it stays indeterminate is theindeterminateprop's decision, not the browser's (checkbox.test.tsx › indeterminate is the DOM property and data-state).data-stateischecked,uncheckedorindeterminate. It follows the props for a controlled checkbox, and the native state after each change for an uncontrolled one. The default theme styles:checkedand:indeterminatefirst, so nothing depends on this attribute after aform.reset()(checkbox.test.tsx › data-state follows the native state).- No form state.
defaultCheckedandnamework in a plain form (FormDatahas the value);checkedandonCheckedChangegive a controlled checkbox. The checkbox never copiescheckedinto state (checkbox.test.tsx › works in a plain form: the browser keeps the state and FormData has it,checkbox.test.tsx › a controlled checkbox shows the checked it is given). aria-invalidon a standalone Checkbox when its Field isinvalid. A Checkbox in a group gets onlydata-invalidfrom the group (checkbox-group.a11y.md).- The error of a standalone checkbox (a declaration) is the Field.ErrorMessage, under the row, in
aria-describedbyafter the option's help text. - Disabled. A Field's
disabledor the prop gives nativedisabledanddata-disabled. The label of a disabled choice is muted by the theme, never hidden. Put the reason for a disabled checkbox in visible help text, never in a tooltip. The help text stays in itsaria-describedby. Tab skips a disabled checkbox (a standalone control), and Checkbox has no focusable disabled state. - Dev warnings (once): a Checkbox in a Field with no Field.Label (no accessible name, 1.3.1/4.1.2); an
idinside a Field (ignored: setcontrolIdon the Field); a Checkbox with no accessible name at all.
It announces nothing.
What you need to do#
- Put the Checkbox directly in
Field.Root, before theField.Label, so the box is at the inline start and the theme's choice layout applies. - A visible label always. The label is the whole sentence for a declaration ("I confirm that the information is correct"), written so it can be answered "yes".
- For a single consent or declaration, set
requiredon the Field, so the label has no "(optional)" and the field isaria-required; ormarker="none". - Own
indeterminate: set it from your data (some, not all, children are checked) and passfalseonce the user has chosen. Don't use it for a checkbox that was never answered. - Validate and set
invalidyourself; render a Field.ErrorMessage that says what to do ("Confirm that the information is correct"). - On a failed send, move focus to the ErrorSummary or to the first invalid field. The Checkbox's error is not live and is read only when the box gets focus (3.3.1 Error Identification (A), 4.1.3 Status Messages (AA)).
- Don't use a checkbox where a Switch or a button is meant (a setting that is saved at once is a Switch), and don't use one for "yes or no" questions that need both answers: use a RadioGroup.
Warning: Don't forget
Give every checkbox a visible Field.Label. Without one, a screen reader says only “checkbox” and nobody knows what is being asked (4.1.2 Name, Role, Value; 3.3.2 Labels or Instructions). A development warning says so.
Visual and modes#
- Focus indicator: on keyboard focus, a ring at least 2px thick, set off from the box, with at least 3:1 contrast against the adjacent colours, drawn around the box (2.4.7 Focus Visible (AA); 2.4.13 Focus Appearance (AAA)).
- Target size: the box is 24 × 24 CSS px, the minimum of 2.5.8 Target Size (Minimum) (AA). The whole row is the target: the label spans the row and is at least 24px high in every density (2.5.8).
- Colour: the box's edge has at least 3:1 contrast against its background (1.4.11 Non-text Contrast (AA)). Checked and indeterminate boxes are filled, with a drawn tick or dash in a contrasting colour. Unchecked and checked differ in shape (a mark appears), not only in colour (1.4.1 Use of Color (A)). An invalid box has a thicker edge plus the error message, never colour alone. A disabled box has a dashed edge, and its label is muted, never hidden.
- forced-colors behaviour (Windows contrast themes): the tick and dash are drawn as shapes and take the system's colours. Checked and indeterminate boxes use the highlight colour for fill and edge, with a highlight-text mark. An invalid box has a thick edge in the text colour. A disabled box has a dashed edge in the disabled-text colour.
- reduced-motion behaviour: the edge and fill change with a transition only when motion is allowed. The mark appears instantly.
- RTL: the box is at the right, the check mark doesn't mirror.
Focus management#
- Initial focus: not moved.
- Trap: no.
- Restore to: not applicable.
- Never obscured by: the focus ring is drawn around the box, outside it, and nothing around clips it (2.4.11 Focus Not Obscured (Minimum) (AA); 2.4.13 Focus Appearance (AAA)). Consumers with a sticky header set
scroll-padding.
WCAG success criteria#
- 1.3.1 Info and Relationships (A), 4.1.2 Name, Role, Value (A): native checkbox, label
for, mixed state from the DOM property. - 1.4.1 Use of Color (A), 1.4.11 Non-text Contrast (AA): the mark's shape, the edge and the invalid width.
- 1.4.3 Contrast (Minimum) (AA): the label, help and error text use the theme's text colours, whose contrast pairs are measured in every theme.
- 2.1.1 Keyboard (A), 2.4.3 Focus Order (A): native Tab and Space.
- 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA), 2.4.13 Focus Appearance (AAA, not counted toward the AA bar).
- 2.5.3 Label in Name (A), 2.5.8 Target Size (Minimum) (AA): the visible label is the name; the box is 24 × 24 CSS px and the whole row is the target.
- 3.3.1 Error Identification (A), 3.3.2 Labels or Instructions (A), 3.3.3 Error Suggestion (AA): the Field's error and help text.
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
Each checkbox is its own Tab stop, also inside a CheckboxGroup: checkboxes are independent, not a composite. Nothing is intercepted: Space, Enter and Tab keep their native behaviour.
| Key | Where | What happens |
|---|---|---|
| Tab | before the checkbox | Moves focus to the checkbox. Each checkbox is one Tab stop Test: checkbox.test.tsx › Tab moves to each checkbox, one stop each |
| Shift+Tab | on a checkbox | Moves focus to the previous focusable element Test: checkbox.test.tsx › Shift+Tab moves to the previous checkbox |
| Tab | disabled checkbox | Skips it (native disabled leaves the Tab sequence)Test: checkbox.test.tsx › Tab skips a disabled checkbox |
| Space | on a checkbox | Toggles it, and reports onCheckedChange (native)Test: checkbox.test.tsx › Space toggles the checkbox |
| Space | on an indeterminate box | Toggles the underlying state (native); with checked={false}, as in the docs example, it checks itTest: checkbox.test.tsx › Space on an indeterminate checkbox checks it |
| Enter | on a checkbox | Doesn't toggle it. In a form the browser may submit it (native, never prevented) Test: checkbox.test.tsx › Enter does not toggle the checkbox and is not intercepted |
The arrow keys, Home and End do nothing on a checkbox (native). Clicking the label, or the padding around the box, toggles it and focuses it (checkbox.test.tsx › clicking the label text toggles the checkbox and focuses it).
API reference#
import { Checkbox, Field, useCheckbox } from '@kvirn-ui/react'Checkbox
Renders <input type="checkbox"> with the role checkbox. It takes every attribute of an <input> except type, and passes ref to it. Put it directly in a Field.Root, before the Field.Label. The label, help text and error are the Field’s parts. The default theme is described on Theming.
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | – | Controlled: the state from your form logic. Pair it with onCheckedChange. The checkbox never copies it into state of its own. |
defaultChecked | boolean | – | Uncontrolled: the browser keeps the state, and a form submit sends it. |
indeterminate | boolean | false | The mixed state, set as the DOM property after render. A click never clears it: you pass false once the user has chosen. |
value | string | – | What a form submit sends when checked, and the option’s value in a CheckboxGroup. |
name | string | – | The name a form submit uses. In a CheckboxGroup, the group’s name is the default and yours wins. |
disabled | boolean | false | Native disabled: skipped by Tab. A disabled Field disables the checkbox too, and the group can too. |
onCheckedChange | (checked: boolean, details: CheckboxChangeDetails) => void | – | Called on every change with the new state and { reason: "input", event }. It only reports. onChange still works too. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-checkbox | always | The part class. The default theme styles it. |
data-state | "checked", "unchecked" or "indeterminate" | Follows the props when controlled, and the native state after each change when not. |
data-invalid | present or absent | The Field or the CheckboxGroup is invalid. |
data-required | present or absent | The Field is required. |
data-disabled | present or absent | The Field, the group or the disabled prop disables it. |
data-focus-visible | present or absent | The checkbox has keyboard focus (:focus-visible). |
aria-invalid | "true" or absent | Set when its Field is invalid. A checkbox in an invalid group gets only data-invalid. |
aria-required | "true" or absent | Set when its Field is required. Not passed directly. |
useCheckbox
Options
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | – | Controlled: the state from your form logic. |
defaultChecked | boolean | – | Uncontrolled: the browser keeps the state. |
indeterminate | boolean | false | The mixed state, set as the DOM property. You clear it, a click does not. |
value | string | – | The value a form submit sends, and the option’s value in a CheckboxGroup. |
name | string | – | The name a form submit uses. In a CheckboxGroup, the group’s name is the default. |
disabled | boolean | false | Native disabled. |
onCheckedChange | (checked: boolean, details: CheckboxChangeDetails) => void | – | Called with the new checked state on every change. It only reports. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
inputProps | CheckboxPartProps | – | Spread on an <input type="checkbox">: class, type, Field wiring, state attributes and handlers. Includes a ref that sets the DOM indeterminate property, so merge it with yours. |
isIndeterminate | boolean | – | The indeterminate option. |
isInvalid | boolean | – | Whether the Field or the CheckboxGroup is invalid. |
isRequired | boolean | – | Whether the Field is required. |
isDisabled | boolean | – | Whether the checkbox is disabled. |
isFocusVisible | boolean | – | Whether the checkbox has keyboard (:focus-visible) focus. |
Known issues#
indeterminatecan't be server-rendered. The DOM property is set in a layout effect, so the first paint of server markup is unchecked, and a mixed box looks unchecked until the script runs. The component test covers the client (the DOM property anddata-state).data-stateafterform.reset(). For an uncontrolled checkbox it's updated on change events, not on a form reset. The theme styles:checkedand:indeterminate, so the look is right; read the native state, not the attribute, in your own code.- The check and dash marks are not tested automatically. They are drawn with
::beforeandclip-pathon the input. No automated test shows that Firefox and WebKit (Safari's engine, not run locally) draw them, or that checked and indeterminate differ visibly from unchecked. The marks are reviewed by eye, so check them in Windows Contrast Themes yourself. A hidden indicator element is the fallback if a browser doesn't draw them.
Testing#
The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.
| AT + browser + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | checkbox.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | checkbox.test.tsx (axe and role, name and state): the Field’s label is the name, and the description is the option’s help text |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 6 rows, each names a test in checkbox.test.tsx |
| Focus order and management | pass | n/a | pass | checkbox.test.tsx: clicking the label text toggles the checkbox and focuses it |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |
What to check#
With a screen reader and the keyboard, try:
- Tab to the box: the label, "checkbox", the state and the help text are read.
- Press Space: the state changes and is read.
- Enter in a form does not toggle the box.
- Click the label: the box toggles and takes focus.
- A "select all" box with some rows chosen reads "mixed".
- Send a declaration unchecked: focus moves to the box and the error is read.
- With voice control, say the visible label to check the box.