Skip to main content

Checkbox

Headless checkbox component providing accessible form input primitives with zero styling opinions. Pair it with the Field primitive to get label, description, and error-message wiring with coordinated ARIA IDs.

Live Demo​

JavaScript
<Field.Root className='checkbox-demo-container' invalid>
<div className='checkbox-row'>
  <Checkbox className='checkbox' name="terms">
    {({ checked }) => (
      <span className='checkbox-indicator'>
        {checked === true && '✓'}
        {checked === 'indeterminate' && '−'}
      </span>
    )}
  </Checkbox>
  <Field.Label className='label'>I accept the terms of service</Field.Label>
</div>
<Field.Description className='description'>
  Helper text for guidance
</Field.Description>
<Field.ErrorMessage className='error'>
  This field is required
</Field.ErrorMessage>
</Field.Root>

The live demo shows the recommended pattern: a Field wrapper supplying label, helper text, and error message wiring around the Checkbox primitive.

Features​

  • ✅ Field integration - Inherits invalid, disabled, required, readOnly from parent <Field>
  • ✅ Dual-state and tri-state support - Boolean checked/unchecked and indeterminate states
  • ✅ Form integration - Hidden input for native form submission with name/value attributes
  • ✅ Controlled and uncontrolled modes - Works with or without external state management
  • ✅ Render props pattern - Access to internal state via children function
  • ✅ Polymorphic rendering - Customizable root element via as prop
  • ✅ Interaction states - Focus, hover, pressed, and disabled state tracking
  • ✅ Auto-focus support - Focus on mount capability
  • ✅ Coordinated ARIA IDs - Automatic aria-labelledby, aria-describedby wiring with Field

Import​

import { Checkbox, Field } from '@turkish-technology/spar';

Checkbox is a self-contained interactive element. Label, description, and error message are owned by the Field primitive:

// Dot notation
<Field.Root>
<Field.Label />
<Checkbox />
<Field.Description />
<Field.ErrorMessage />
</Field.Root>;

// Named import style
import {
Field,
FieldLabel,
FieldDescription,
FieldErrorMessage,
Checkbox,
} from '@turkish-technology/spar';

<Field>
<FieldLabel />
<Checkbox />
<FieldDescription />
<FieldErrorMessage />
</Field>;

Anatomy​

The Checkbox component focuses on the interactive element itself. Label, description, and error message are provided by the Field primitive, which shares ARIA IDs and state with Checkbox via context.

✓
Helper text for guidance
Parts
Field.RootField context provider (label, description, error wiring)
Field.LabelAccessible label, auto-linked via aria-labelledby
CheckboxSelf-contained checkbox element with state management, accessibility, and interaction handling
Field.DescriptionHelper text for guidance
Field.ErrorMessageError announcement with role="alert"

Structure​

<Checkbox>
{({ checked }) => <span className="indicator">{checked && '✓'}</span>}
</Checkbox>

With Field:

<Field.Root required invalid>
<div className="checkbox-row">
<Checkbox name="fieldName">
{({ checked }) => <span className="indicator">{checked && '✓'}</span>}
</Checkbox>
<Field.Label>Label text</Field.Label>
</div>
<Field.Description>Description text</Field.Description>
<Field.ErrorMessage>Error text</Field.ErrorMessage>
</Field.Root>

Data Flow:

  • User interaction (click/keyboard) → State change → ARIA updates → Form submission (if form context)
  • Checkbox manages internal checked state (controlled or uncontrolled)
  • When inside a Field, Checkbox inherits invalid, disabled, required, readOnly automatically
  • Hidden input synchronizes with checkbox state for native form integration
  • ARIA attributes (aria-labelledby, aria-describedby) are automatically wired from Field's coordinated IDs

Code Examples​

Basic Usage​

Use a render function when you want the visual checkmark to appear only in the checked state.

function BasicCheckbox() {
return (
<Checkbox>
{({ checked }) => <span className="indicator">{checked ? '✓' : ''}</span>}
</Checkbox>
);
}

Controlled State​

Manage the checked value in parent state when the checkbox needs to stay in sync with other UI.

function ControlledCheckbox() {
const [isChecked, setIsChecked] = useState<boolean>(false);

return (
<Field.Root>
<div className="checkbox-row">
<Checkbox checked={isChecked} onChange={setIsChecked}>
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Field.Label>Subscribe to newsletter</Field.Label>
</div>
</Field.Root>
);
}

Indeterminate State​

Use the indeterminate state for mixed selections, such as a parent checkbox that represents partially selected children.

The indeterminate prop layers the mixed state (aria-checked="mixed", data-state="indeterminate") on top of checked/defaultChecked without taking ownership of the value, so it works in both modes. A user toggle still fires onChange(true) and, in uncontrolled mode, advances the internal boolean state underneath, so clearing indeterminate from onChange lands on the new state instead of a stale mixed value:

function SelectAllCheckbox() {
const [indeterminate, setIndeterminate] = useState(true);

return (
<Field.Root>
<div className="checkbox-row">
<Checkbox
indeterminate={indeterminate}
onChange={() => setIndeterminate(false)}
>
{({ checked }) => (
<span className="indicator">
{checked === true && '✓'}
{checked === 'indeterminate' && '−'}
</span>
)}
</Checkbox>
<Field.Label>Select all items</Field.Label>
</div>
</Field.Root>
);
}

Alternatively, keep the whole tri-state value under your control with checked='indeterminate':

function IndeterminateCheckbox() {
const [checked, setChecked] = useState<CheckedState>('indeterminate');

const handleChange = (newChecked: CheckedState) => {
if (newChecked === true) {
setChecked(false);
} else if (newChecked === false) {
setChecked('indeterminate');
} else {
setChecked(true);
}
};

return (
<Field.Root>
<div className="checkbox-row">
<Checkbox checked={checked} onChange={handleChange}>
{({ checked }) => (
<span className="indicator">
{checked === true && '✓'}
{checked === 'indeterminate' && '−'}
</span>
)}
</Checkbox>
<Field.Label>Select all items</Field.Label>
</div>
</Field.Root>
);
}

Form Integration​

Provide name and value when the checkbox should participate in native form submission.

function FormCheckbox() {
return (
<form>
<Field.Root required>
<div className="checkbox-row">
<Checkbox name="terms" value="accepted">
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Field.Label>I agree to the terms</Field.Label>
</div>
</Field.Root>

<Field.Root>
<div className="checkbox-row">
<Checkbox name="newsletter" value="subscribed" defaultChecked={true}>
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Field.Label>Subscribe to newsletter</Field.Label>
</div>
</Field.Root>

<button type="submit">Submit</button>
</form>
);
}

Field Integration​

Wrap a Checkbox in a <Field.Root> to automatically inherit validation state and wire ARIA relationships.

function FieldCheckbox() {
const [accepted, setAccepted] = useState(false);

return (
<div>
<Field.Root required invalid={!accepted}>
<div className="checkbox-row">
<Checkbox name="terms" checked={accepted} onChange={setAccepted}>
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Field.Label>Terms & Conditions</Field.Label>
</div>
<Field.Description>You must accept to proceed.</Field.Description>
<Field.ErrorMessage>Please accept the terms.</Field.ErrorMessage>
</Field.Root>

<Field.Root disabled>
<div className="checkbox-row">
<Checkbox name="archive">
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Field.Label>Archived Option</Field.Label>
</div>
<Field.Description>
This option is currently unavailable.
</Field.Description>
</Field.Root>
</div>
);
}

Render Props Pattern​

The render-props API exposes interaction state so you can build custom visuals without reimplementing behavior.

function RenderPropsCheckbox() {
return (
<Checkbox defaultChecked={false}>
{({
checked,
disabled,
invalid,
required,
isFocused,
isHovered,
isPressed,
}) => (
<div>
<span>{checked ? '✓' : '☐'}</span>
<span>Invalid: {invalid ? 'Yes' : 'No'}</span>
<span>Focused: {isFocused ? 'Yes' : 'No'}</span>
<span>Hovered: {isHovered ? 'Yes' : 'No'}</span>
<span>Pressed: {isPressed ? 'Yes' : 'No'}</span>
</div>
)}
</Checkbox>
);
}

Disabled State​

Disabled checkboxes remain readable but do not respond to pointer or keyboard input.

function DisabledCheckbox() {
return (
<div>
<Checkbox disabled>
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Checkbox disabled defaultChecked={true}>
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Checkbox disabled checked="indeterminate">
{({ checked }) => (
<span className="indicator">
{checked === 'indeterminate' ? '−' : ''}
</span>
)}
</Checkbox>
</div>
);
}

Custom Element with Polymorphic Rendering​

Render the checkbox as another element when your layout needs a custom wrapper.

function CustomElementCheckbox() {
return (
<Checkbox as="button">
{({ checked }) => <span className="indicator">{checked ? '✓' : ''}</span>}
</Checkbox>
);
}

Accessibility Enhanced with Field​

Combine Field integration for automatic ARIA wiring with validation feedback.

function AccessibleCheckbox() {
const [hasError, setHasError] = useState(true);

return (
<Field.Root required invalid={hasError}>
<div className="checkbox-row">
<Checkbox onChange={checked => setHasError(!checked)}>
{({ checked }) => (
<span className="indicator">{checked ? '✓' : ''}</span>
)}
</Checkbox>
<Field.Label>Agreement</Field.Label>
</div>
<Field.Description>This field is required to continue.</Field.Description>
<Field.ErrorMessage>⚠️ This field is required</Field.ErrorMessage>
</Field.Root>
);
}

API Reference​

Checkbox​

A self-contained headless checkbox component with full accessibility and Field integration. When nested inside a <Field>, it reads the Field's state automatically.

Props

NameTypeDefaultDescription
as?React.ElementType'span'The element or component to render as
ref?React.Ref<HTMLElement>undefinedRef to the underlying DOM element
checked?CheckedStateundefinedControlled checked state. When provided, component operates in controlled mode
defaultChecked?CheckedStatefalseDefault checked state for uncontrolled usage
indeterminate?booleanfalseShows the mixed state on top of checked/defaultChecked without owning the value
onChange?(checked: CheckedState) => voidundefinedCallback fired when the checked state changes
disabled?booleanfalseDisabled state - prevents interaction and is properly announced to screen readers
name?stringundefinedName attribute for form submission
value?string'on'Value sent in form data when checked
form?stringundefinedID of the form this checkbox belongs to
required?booleanfalseRequired state for form validation
readOnly?booleanfalseRead-only state - prevents interaction
invalid?booleanfalseInvalid/error state. Inherited from Field unless explicitly overridden
autoFocus?booleanfalseAuto-focus on mount
children?React.ReactNode | ((state: CheckboxRenderProps) => React.ReactNode)undefinedContent to display, or render props function
id?stringauto-generatedUnique identifier for the checkbox
className?stringundefinedCSS class name
style?React.CSSPropertiesundefinedInline styles
tabIndex?number0Tab index for keyboard navigation

CheckboxRenderProps​

When using the render props pattern, the following state properties are passed to the children function:

PropertyTypeDescription
checkedCheckedStateCurrent checked state (true, false, or 'indeterminate')
setChecked(checked: CheckedState) => voidFunction to programmatically set the checked state
disabledbooleanWhether the checkbox is disabled
readOnlybooleanWhether the checkbox is read-only
requiredbooleanWhether the checkbox is required
invalidbooleanWhether the checkbox is in an invalid/error state
isFocusedbooleanWhether the checkbox currently has focus
isHoveredbooleanWhether the checkbox is being hovered
isPressedbooleanWhether the checkbox is being pressed

Events

NameParametersDescriptionWhen Triggered
onChange(checked: CheckedState)Checked state changesUser clicks, presses Space, or programmatic change
onClick(event: React.MouseEvent)Element clickedMouse click on checkbox
onKeyDown(event: React.KeyboardEvent)Key pressedKeyboard interaction (Space toggles)
onFocus(event: React.FocusEvent)Element gains focusFocus enters checkbox
onBlur(event: React.FocusEvent)Element loses focusFocus leaves checkbox

Data Attributes

AttributeValuePurpose
data-checked""Present when checked is true
data-indeterminate""Present when checked is 'indeterminate' or indeterminate is set
data-disabled""Present when disabled is true
data-readonly""Present when readOnly is true
data-required""Present when required is true
data-invalid""Present when invalid is true
data-focus""Present when the checkbox has focus
data-hover""Present when the checkbox is hovered
data-active""Present when the checkbox is being pressed

Keyboard Interactions​

KeyActionContextNotes
TabNavigate to checkboxAlwaysMoves focus to the checkbox
Shift + TabNavigate backwardAlwaysMoves focus away from checkbox
SpaceToggle checked stateFocusedPrimary activation method for checkboxes
EnterSubmit formIn form contextDoes not toggle state, submits parent form

Note: The checkbox follows WCAG guidelines where Space is the primary toggle key, while Enter submits forms without changing checkbox state.