Checkbox
Checkboxes let users select one or more items from a list, or turn an item on or off.
Maps
Checkboxes let people select one or more items from a list, or turn an item on or off. Use them to:
- Select one or more options from a list
- Present a list that contains sub-selections
- Turn an item on or off in a desktop environment
- Group similar options together
Compared with the other selection controls:
- Checkbox or switch: Use checkboxes in place of switches when several related options can be selected from a list. Checkboxes group similar items together and take up less space than switches.
- Checkbox or radio button: Checkboxes are multi-select. To select a single option from a set, use radio buttons.
Use a Checkbox on its own, or several in a group, which is composed of these parts:
| Part | Use |
|---|---|
CheckboxGroup | The group, which holds the other parts |
Label | The group's name. Without one, name the group with an aria-label. |
Checkbox | A checkbox. In a group, an option, with its value. |
Text with slot="description" | The group's description |
FieldError | The group's error, displayed once a form submission is blocked. See Forms. |
import { Checkbox, CheckboxGroup } from '@material-web/react'
import { FieldError, Label, Text } from 'react-aria-components'Basic checkbox
Use a Checkbox on its own, or put several in a CheckboxGroup to select from a list. Set defaultSelected on a checkbox that starts selected.
import { Checkbox } from '@material-web/react'
export default function Basic() {
return (
<div className="flex flex-col items-start text-body-lg">
<Checkbox defaultSelected>Pickles</Checkbox>
<Checkbox>Tomato</Checkbox>
<Checkbox>Lettuce</Checkbox>
</div>
)
}Set isDisabled to disable the checkbox: it cannot be selected or focused. Set isReadOnly to keep its selection as it is while it can still be focused.
import { Checkbox } from '@material-web/react'
export default function Disabled() {
return (
<div className="flex flex-col items-start text-body-lg">
<Checkbox isDisabled>Pickles</Checkbox>
<Checkbox isDisabled defaultSelected>
Tomato
</Checkbox>
<Checkbox isDisabled isIndeterminate>
Lettuce
</Checkbox>
</div>
)
}Label
Write the label as the checkbox's children. Pressing the label toggles the checkbox. With no label text, set an aria-label.
import { Checkbox } from '@material-web/react'
export default function WithLabel() {
return (
<>
<Checkbox defaultSelected className="text-body-lg">
Remember me
</Checkbox>
<Checkbox aria-label="Select all messages" />
</>
)
}The label takes the type style of the text around it. To set one, add its class to the checkbox or to an element around it, as in text-body-lg.
Checkbox group
Put checkboxes in a CheckboxGroup and give each a value. The group's value is the list of the selected values, as with React Aria's CheckboxGroup.
The group has no layout of its own, so give it one, such as a column.
import { Checkbox, CheckboxGroup } from '@material-web/react'
import { Label, Text } from 'react-aria-components'
export default function Group() {
return (
<CheckboxGroup
name="extras"
defaultValue={['pickles', 'cheese']}
className="flex flex-col items-start text-body-lg"
>
<Label className="ps-space-150 text-label-lg text-on-surface-variant">Extras</Label>
<Checkbox value="pickles">Pickles</Checkbox>
<Checkbox value="tomato">Tomato</Checkbox>
<Checkbox value="lettuce">Lettuce</Checkbox>
<Checkbox value="cheese">Cheese</Checkbox>
<Text slot="description" className="ps-space-150 text-body-sm text-on-surface-variant">
Free of charge
</Text>
</CheckboxGroup>
)
}Set the initial selection with defaultValue, or control it with value and onChange. In a group, a checkbox's own isSelected and defaultSelected do not change the group's value.
import { Checkbox, CheckboxGroup } from '@material-web/react'
import { useState } from 'react'
export default function GroupControlled() {
const [extras, setExtras] = useState(['tomato'])
return (
<div className="flex flex-col items-start text-body-lg">
<CheckboxGroup
aria-label="Extras"
value={extras}
onChange={setExtras}
className="flex flex-col items-start"
>
<Checkbox value="pickles">Pickles</Checkbox>
<Checkbox value="tomato">Tomato</Checkbox>
<Checkbox value="lettuce">Lettuce</Checkbox>
</CheckboxGroup>
<span className="ps-space-150 text-body-md text-on-surface-variant">
{extras.length > 0 ? `With ${extras.join(', ')}` : 'No extras'}
</span>
</div>
)
}The group's other props apply to every checkbox in it:
isDisabledandisReadOnlydisable each checkbox or make it read-only.isInvalidshows each checkbox in the error color.isRequiredrequires at least one checkbox to be selected.namesubmits each selectedvalueunder that name.
Slots
- description
| Slot | Child | Use |
|---|---|---|
description | A Text | Describes the group and each checkbox in it |
Controlled
Control the selection with isSelected and onChange, which is called with the new selection. Without them, the checkbox keeps its own selection, starting from defaultSelected.
import { Checkbox } from '@material-web/react'
import { useState } from 'react'
export default function Controlled() {
const [isSelected, setSelected] = useState(true)
return (
<div className="flex flex-col items-start text-body-lg">
<Checkbox isSelected={isSelected} onChange={setSelected}>
Email me the receipt
</Checkbox>
<span className="ps-space-500 text-body-md text-on-surface-variant">
{isSelected ? 'A receipt will be sent' : 'No receipt will be sent'}
</span>
</div>
)
}Indeterminate
Set isIndeterminate to show a dash in place of the check. A press does not clear it, so clear it yourself in onChange.
In this example, a parent checkbox is indeterminate while only some of its children are selected. Selecting the parent selects every child, and unselecting it unselects them all.
import { Checkbox } from '@material-web/react'
import { useState } from 'react'
const extras = ['Pickles', 'Tomato', 'Lettuce']
export default function Indeterminate() {
const [selected, setSelected] = useState(['Tomato'])
const isAll = selected.length === extras.length
return (
<div className="flex flex-col items-start text-body-lg">
<Checkbox
isSelected={isAll}
isIndeterminate={selected.length > 0 && !isAll}
onChange={(isSelected) => setSelected(isSelected ? extras : [])}
>
Additions
</Checkbox>
{extras.map((name) => (
<Checkbox
key={name}
className="ps-space-400"
isSelected={selected.includes(name)}
onChange={(isSelected) =>
setSelected(isSelected ? [...selected, name] : selected.filter((it) => it !== name))
}
>
{name}
</Checkbox>
))}
</div>
)
}Note: isIndeterminate changes how the checkbox is shown and announced. In a form, the checkbox is still submitted by its selection.
Validation
Set isInvalid to mark the checkbox as invalid and show it in the error color. To show the error of a field that a form requires, see Forms.
import { Checkbox } from '@material-web/react'
export default function Invalid() {
return (
<>
<Checkbox isInvalid aria-label="Unselected" />
<Checkbox isInvalid defaultSelected aria-label="Selected" />
<Checkbox isInvalid isIndeterminate aria-label="Indeterminate" />
</>
)
}Forms
Set a name to include a checkbox or a group in a form. It is submitted with the form and reset with it.
| Field | Submits |
|---|---|
A Checkbox with a name | Its value when selected, or on with no value. Nothing when unselected. |
A CheckboxGroup with a name | The value of each selected checkbox, under the group's name. |
Set isRequired to require a single checkbox to be selected, or a group to have at least one checkbox selected. A required field blocks its form from being submitted until then. Once a submission is blocked, each checkbox shows the error color, and a FieldError in the group is displayed, until one is selected. See React Aria's Forms guide.
import { Button, Checkbox, CheckboxGroup } from '@material-web/react'
import { FieldError, Label } from 'react-aria-components'
export default function Required() {
return (
<form
onSubmit={(event) => event.preventDefault()}
className="flex flex-col items-start gap-space-100 text-body-lg"
>
<CheckboxGroup name="extras" isRequired className="flex flex-col items-start">
<Label className="ps-space-150 text-label-lg text-on-surface-variant">Extras</Label>
<Checkbox value="pickles">Pickles</Checkbox>
<Checkbox value="tomato">Tomato</Checkbox>
<Checkbox value="lettuce">Lettuce</Checkbox>
<FieldError className="ps-space-150 text-body-sm text-error">Pick at least one</FieldError>
</CheckboxGroup>
<Button type="submit" className="ms-space-150">
Order
</Button>
</form>
)
}Note: A reset from code, with form.reset(), that unselects several checkboxes of a group unselects only the last of them. A reset button resets them all.
In a list
In a selection list, put a Checkbox in an item's selection, leading or trailing slot to make it the item's selection checkbox. It needs no label.
import { Checkbox, List, ListItem } from '@material-web/react'
import { Text } from 'react-aria-components'
const extras = ['Pickles', 'Tomato', 'Lettuce']
export default function InList() {
return (
<List
aria-label="Extras"
selectionMode="multiple"
defaultSelectedKeys={['Pickles']}
className="w-90"
>
{extras.map((name) => (
<ListItem key={name} id={name} textValue={name}>
<Text slot="label">{name}</Text>
<Checkbox slot="trailing" />
</ListItem>
))}
</List>
)
}Customization
Pass classes in className to restyle one checkbox. They go on its outermost element, an inline flex box aligned to the middle of its line, as do style and ref. inputRef is the ref of its input. See Styling for the classes, the states and the theme.
import { Checkbox } from '@material-web/react'
export default function Custom() {
return (
<div className="flex flex-col items-start gap-space-100 text-body-lg">
<Checkbox className="rounded-shape-full pe-space-200 has-hover:bg-surface-container">
Highlighted on hover
</Checkbox>
<Checkbox
defaultSelected
className="rounded-shape-full pe-space-200 selected:bg-secondary-container"
>
Tinted when selected
</Checkbox>
</div>
)
}- Color:
classNamedoes not reach the box. To change its colors, set the color roles it uses. See Theme. - States: On a checkbox, the variants
selected:,indeterminate:,invalid:,disabled:,read-only:andrequired:style those states. Hover, press and focus are reported on an element inside it, so use theirhas-*form, as inhas-hover:bg-surface-container. See States. - Functions:
classNameandstylecan be functions ofisSelected,isIndeterminate,isInvalid,isDisabled,isReadOnlyandisRequired. To read hover, press and focus, pass a function as children. - Every checkbox: To restyle all the checkboxes at once, change the theme.
Children as a function
Pass a function as children to render the label from the checkbox's state: isSelected, isIndeterminate, isHovered, isPressed, isFocused, isFocusVisible, isDisabled, isReadOnly, isInvalid and isRequired. isFocused is any focus, and isFocusVisible is keyboard focus only. The state's type is exported as CheckboxRenderProps. See Children as a function.
import { Checkbox } from '@material-web/react'
export default function RenderProps() {
return (
<Checkbox className="text-body-lg">
{({ isSelected }) => (isSelected ? 'Notifications are on' : 'Notifications are off')}
</Checkbox>
)
}On a CheckboxGroup, className, style and children can be functions of isDisabled, isReadOnly, isRequired, isInvalid and state, typed as CheckboxGroupRenderProps.
Use cases
Material lists what people should be able to do with assistive technology:
- Navigate to a checkbox
- Toggle the checkbox on and off
- Get appropriate feedback based on input type documented under Interaction & style
Interaction and style
- States: Hovering shows a state layer, and a press shows a ripple. Keyboard focus shows a focus ring, and a press with a mouse or touch does not.
- Touch target: A checkbox has a touch target of 48dp around its box. Pressing its label toggles it too.
- Color contrast: In the light and dark schemes, at every contrast level, the box keeps 3:1 contrast with the surface, and the check with the box's fill. Keep that contrast when you change the color roles it uses.
- Density: Material advises against density that brings a checkbox's target under 48dp. A checkbox does not follow the density classes: it keeps its size and its 48dp target in a denser layout.
- Motion: With reduced motion, the box changes color and draws its check instantly.
- Forced colors: In forced colors, a selected or indeterminate box is filled with the system's highlight color, and a disabled checkbox and its label are grayed out.
- Indeterminate: Material describes a parent checkbox that is indeterminate while only some of its children are selected, and that selects them all when it is selected. Set
isIndeterminateand the children's selection yourself, as in the Indeterminate example.
Focus
- Each checkbox is a tab stop, in a group too.
- A disabled checkbox cannot be focused, and Tab skips it. A read-only checkbox can still be focused.
Keyboard navigation
| Keys | Actions |
|---|---|
| Tab | Move the focus to a checkbox |
| Space | Select or deselect the focused checkbox |
- Enter does not toggle a checkbox.
Labeling elements
- A checkbox has the checkbox role, and its label names it. Material advises a name that is the same as the label text: write the label as the checkbox's children, which links the two. With no label, set an
aria-label. - A group has the group role. Name it with a
Labelor anaria-label. ATextin itsdescriptionslot describes the group and each checkbox in it. - An indeterminate checkbox is announced as partially checked.
isInvalid,isReadOnlyandisRequiredare reported to assistive technology.
Checkbox
Props of Checkbox (40)
classNameClassNameOrFunction<CheckboxFieldRenderProps>Default'react-aria-CheckboxField'The CSS className for the element. A function may be provided to compute the class based on component state.
inputRefRef<HTMLInputElement | null>A ref for the HTML input element.
formstringThe
<form>element to associate the input with. The value of this attribute must be the id of a<form>in the same document. See MDN.idstringThe element's unique identifier. See MDN.
aria-labelstringDefines a string value that labels the current element.
aria-labelledbystringIdentifies the element (or elements) that labels the current element.
aria-describedbystringIdentifies the element (or elements) that describes the object.
aria-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.
onClick(e: MouseEvent<FocusableElement>) => voidNot recommended – use
onPressinstead.onClickis an alias foronPressprovided for compatibility with other libraries.onPressprovides additional event details for non-mouse interactions.isDisabledbooleanWhether the input is disabled.
onPress(e: PressEvent) => voidHandler that is called when the press is released over the target.
onPressStart(e: PressEvent) => voidHandler that is called when a press interaction starts.
onPressEnd(e: PressEvent) => voidHandler that is called when a press interaction ends, either over the target or when the pointer leaves the target.
onPressChange(isPressed: boolean) => voidHandler that is called when the press state changes.
onPressUp(e: PressEvent) => voidHandler that is called when a press is released over the target, regardless of whether it started on the target or not.
autoFocusbooleanWhether the element should receive focus on render.
onFocus(e: FocusEvent<Target>) => voidHandler that is called when the element receives focus.
onBlur(e: FocusEvent<Target>) => voidHandler that is called when the element loses focus.
onFocusChange(isFocused: boolean) => voidHandler that is called when the element's focus status changes.
onKeyDown(e: KeyboardEvent) => voidHandler that is called when a key is pressed.
onKeyUp(e: KeyboardEvent) => voidHandler that is called when a key is released.
aria-controlsstringIdentifies the element (or elements) whose contents or presence are controlled by the current element.
namestringThe name of the input element, used when submitting an HTML form. See MDN.
valuestringThe value of the input element, used when submitting an HTML form. See MDN.
excludeFromTabOrderbooleanWhether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available.
isSelectedbooleanWhether the element should be selected (controlled).
defaultSelectedbooleanWhether the element should be selected (uncontrolled).
onChange(isSelected: boolean) => voidHandler that is called when the element's selection state changes.
isReadOnlybooleanWhether the input can be selected but not changed by the user.
isInvalidbooleanWhether the input value is invalid.
isIndeterminatebooleanIndeterminism is presentational only. The indeterminate visual representation remains regardless of user interaction.
isRequiredbooleanWhether user input is required on the input before form submission.
validate(value: boolean) => true | ValidationError | null | undefinedA function that returns an error message if a given value is invalid. Validation errors are displayed to the user when the form is submitted if
validationBehavior="native". For realtime validation, use theisInvalidprop instead.aria-errormessagestringIdentifies the element that provides an error message for the object.
validationBehavior'native' | 'aria'Default'native'Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA.
styleCSSProperties | (values: CheckboxFieldRenderProps & { defaultStyle: CSSProperties; }) => CSSProperties | undefinedThe inline style for the element. A function may be provided to compute the style based on component state.
renderDOMRenderFunction<'div', CheckboxFieldRenderProps>Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components.
Requirements:
- You must render the expected element type (e.g. if
<button>is expected, you cannot render an<a>). - Only a single root DOM element can be rendered (no fragments).
- You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate.
- You must render the expected element type (e.g. if
slotstring | nullA slot name for the component. Slots allow the component to receive props from a parent component. An explicit
nullvalue indicates that the local props completely override all props received from a parent.childrenChildrenOrFunction<T>The children of the component. A function may be provided to alter the children based on component state.
refRef<HTMLDivElement>
Checkbox also takes the 69 attributes and events of the element it renders.
CheckboxGroup
Props of CheckboxGroup (26)
classNameClassNameOrFunction<CheckboxGroupRenderProps>Default'react-aria-CheckboxGroup'The CSS className for the element. A function may be provided to compute the class based on component state.
formstringThe
<form>element to associate the input with. The value of this attribute must be the id of a<form>in the same document. See MDN.idstringThe element's unique identifier. See MDN.
aria-labelstringDefines a string value that labels the current element.
aria-labelledbystringIdentifies the element (or elements) that labels the current element.
aria-describedbystringIdentifies the element (or elements) that describes the object.
aria-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.
isDisabledbooleanWhether the input is disabled.
onFocus(e: FocusEvent<Target>) => voidHandler that is called when the element receives focus.
onBlur(e: FocusEvent<Target>) => voidHandler that is called when the element loses focus.
onFocusChange(isFocused: boolean) => voidHandler that is called when the element's focus status changes.
namestringThe name of the input element, used when submitting an HTML form. See MDN.
valuestring[]The current value (controlled).
onChange(value: string[]) => voidHandler that is called when the value changes.
isReadOnlybooleanWhether the input can be selected but not changed by the user.
isInvalidbooleanWhether the input value is invalid.
defaultValuestring[]The default value (uncontrolled).
isRequiredbooleanWhether user input is required on the input before form submission.
validate(value: string[]) => true | ValidationError | null | undefinedA function that returns an error message if a given value is invalid. Validation errors are displayed to the user when the form is submitted if
validationBehavior="native". For realtime validation, use theisInvalidprop instead.aria-errormessagestringIdentifies the element that provides an error message for the object.
validationBehavior'native' | 'aria'Default'native'Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA.
childrenChildrenOrFunction<T>The children of the component. A function may be provided to alter the children based on component state.
styleCSSProperties | (values: CheckboxGroupRenderProps & { defaultStyle: CSSProperties; }) => CSSProperties | undefinedThe inline style for the element. A function may be provided to compute the style based on component state.
renderDOMRenderFunction<'div', CheckboxGroupRenderProps>Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components.
Requirements:
- You must render the expected element type (e.g. if
<button>is expected, you cannot render an<a>). - Only a single root DOM element can be rendered (no fragments).
- You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate.
- You must render the expected element type (e.g. if
slotstring | nullA slot name for the component. Slots allow the component to receive props from a parent component. An explicit
nullvalue indicates that the local props completely override all props received from a parent.refRef<HTMLDivElement>
CheckboxGroup also takes the 70 attributes and events of the element it renders.