packages/react-aria-components/docs/CheckboxGroup.mdx
{/* Copyright 2020 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */}
import {Layout} from '@react-spectrum/docs'; export default Layout;
import docs from 'docs:react-aria-components'; import statelyDocs from 'docs:@react-stately/checkbox'; import typesDocs from 'docs:@react-types/shared/src/events.d.ts'; import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable, VersionBadge, ClassAPI} from '@react-spectrum/docs'; import styles from '@react-spectrum/docs/src/docs.css'; import packageData from 'react-aria-components/package.json'; import Anatomy from '/packages/react-aria/docs/checkbox/checkboxgroup-anatomy.svg'; import ChevronRight from '@spectrum-icons/workflow/ChevronRight'; import {Divider} from '@react-spectrum/divider'; import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard'; import {Keyboard} from '@react-spectrum/text'; import Label from '@react-spectrum/docs/pages/assets/component-illustrations/Label.svg'; import Form from '@react-spectrum/docs/pages/assets/component-illustrations/Form.svg'; import {StarterKits} from '@react-spectrum/docs/src/StarterKits';
<PageDescription>{docs.exports.CheckboxGroup.description}</PageDescription>
<HeaderInfo packageData={packageData} componentNames={['CheckboxGroup']} sourceData={[ {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/'} ]} />
import {CheckboxGroup, Checkbox, Label} from 'react-aria-components';
<CheckboxGroup>
<Label>Favorite sports</Label>
<Checkbox value="soccer">
<div className="checkbox" aria-hidden="true">
<svg viewBox="0 0 18 18"><polyline points="1 9 7 14 15 4" /></svg>
</div>
Soccer
</Checkbox>
<Checkbox value="baseball">
<div className="checkbox" aria-hidden="true">
<svg viewBox="0 0 18 18"><polyline points="1 9 7 14 15 4" /></svg>
</div>
Baseball
</Checkbox>
<Checkbox value="basketball">
<div className="checkbox" aria-hidden="true">
<svg viewBox="0 0 18 18"><polyline points="1 9 7 14 15 4" /></svg>
</div>
Basketball
</Checkbox>
</CheckboxGroup>
@import "@react-aria/example-theme";
.react-aria-CheckboxGroup {
display: flex;
flex-direction: column;
gap: 0.571rem;
color: var(--text-color);
}
Checkbox groups can be built in HTML with the
<fieldset>
and <input> elements,
however these can be difficult to style. CheckboxGroup helps achieve accessible
checkbox groups that can be styled as needed.
<Label>. Description and error message help text slots are supported as well.<input> element under the hood, which enables HTML form integration and autofill.A checkbox group consists of a set of checkboxes, and a label. Each checkbox includes a label and a visual selection indicator. Zero or more checkboxes within the group can be selected at a time. Users may click or touch a checkbox to select it, or use the <Keyboard>Tab</Keyboard> key to navigate to it and the <Keyboard>Space</Keyboard> key to toggle it.
CheckboxGroup also supports optional description and error message elements, which can be used
to provide more context about the field, and any validation messages. These are linked with the
inputs via the aria-describedby attribute.
import {CheckboxGroup, Checkbox, Label, Text, FieldError} from 'react-aria-components';
<CheckboxGroup>
<Label />
<Checkbox />
<Text slot="description" />
<FieldError />
</CheckboxGroup>
Individual checkboxes must have a visual label. If the checkbox group does not have a visible label,
an aria-label or aria-labelledby prop must be passed instead to identify the element to assistive
technology.
CheckboxGroup makes use of the following concepts:
<ExampleCard url="forms.html" title="Forms" description="Validating and submitting form data, and integrating with form libraries.">
<Form /> </ExampleCard> </section>A CheckboxGroup uses the following components, which may also be used standalone or reused in other components.
<ExampleCard url="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label" title="Label" description="A label provides context for an element."> <Label /> </ExampleCard>
</section>To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured Storybook that you can experiment with, or use as a starting point for your own component library.
<StarterKits component="checkboxgroup" />If you will use a CheckboxGroup in multiple places in your app, you can wrap all of the pieces into a reusable component. This way, the DOM structure, styling code, and other logic are defined in a single place and reused everywhere to ensure consistency.
This example wraps CheckboxGroup and all of its children together into a single component which accepts a label prop, which is passed to the right place. It also shows how to use the description slot to render help text, and FieldError component to render validation errors.
import type {CheckboxGroupProps, CheckboxProps, ValidationResult} from 'react-aria-components';
import {Text, FieldError} from 'react-aria-components';
interface MyCheckboxGroupProps extends Omit<CheckboxGroupProps, 'children'> {
children?: React.ReactNode,
label?: string,
description?: string,
errorMessage?: string | ((validation: ValidationResult) => string)
}
export function MyCheckboxGroup({
label,
description,
errorMessage,
children,
...props
}: MyCheckboxGroupProps) {
return (
<CheckboxGroup {...props}>
{label && <Label>{label}</Label>}
{children}
{description && <Text slot="description">{description}</Text>}
<FieldError>{errorMessage}</FieldError>
</CheckboxGroup>
);
}
interface MyCheckboxProps extends Omit<CheckboxProps, 'children'> {
children?: React.ReactNode
}
function MyCheckbox({children, ...props}: MyCheckboxProps) {
return (
<Checkbox {...props}>
<div className="checkbox" aria-hidden="true">
<svg viewBox="0 0 18 18"><polyline points="1 9 7 14 15 4" /></svg>
</div>
{children}
</Checkbox>
);
}
<MyCheckboxGroup label="Favorite sports">
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball">Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>
An initial, uncontrolled value can be provided to the CheckboxGroup using the defaultValue prop, which accepts an array of selected items that map to the
value prop on each Checkbox.
<MyCheckboxGroup label="Favorite sports (uncontrolled)" defaultValue={['soccer', 'baseball']}>
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball">Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>
A controlled value can be provided using the value prop, which accepts an array of selected items, which map to the
value prop on each Checkbox. The onChange event is fired when the user checks or unchecks an option. It receives a new array
containing the updated selected values.
function Example() {
let [selected, setSelected] = React.useState(['soccer', 'baseball']);
return (
<MyCheckboxGroup label="Favorite sports (controlled)" value={selected} onChange={setSelected}>
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball">Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>
);
}
CheckboxGroup supports the name prop, paired with the Checkbox value prop, for integration with HTML forms.
<MyCheckboxGroup label="Favorite sports" name="sports">
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball">Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>
CheckboxGroup supports the isRequired prop to ensure the user selects at least one item, as well as custom client and server-side validation. Individual checkboxes also support validation, and errors from all checkboxes are aggregated at the group level. CheckboxGroup can also be integrated with other form libraries. See the Forms guide to learn more.
The isRequired prop at the CheckboxGroup level requires that at least one item is selected. To display validation errors, add a <FieldError> element as a child of the CheckboxGroup. This allows you to render error messages from all of the above sources with consistent custom styles.
import {Form, FieldError, Button} from 'react-aria-components';
<Form>
<CheckboxGroup name="condiments" isRequired>
<Label>Sandwich condiments</Label>
<MyCheckbox value="lettuce">Lettuce</MyCheckbox>
<MyCheckbox value="tomato">Tomato</MyCheckbox>
<MyCheckbox value="onion">Onion</MyCheckbox>
<MyCheckbox value="sprouts">Sprouts</MyCheckbox>
<FieldError />
</CheckboxGroup>
<Button type="submit">Submit</Button>
</Form>
.react-aria-CheckboxGroup {
.react-aria-FieldError {
font-size: 12px;
color: var(--invalid-color);
}
}
By default, FieldError displays default validation messages provided by the browser. See Customizing error messages in the Forms guide to learn how to provide your own custom errors.
To require that specific checkboxes are checked, set the isRequired prop at the Checkbox level instead of the CheckboxGroup. The following example shows how to require that all items are selected.
<Form>
<CheckboxGroup>
<Label>Agree to the following</Label>
<MyCheckbox value="terms" isRequired>Terms and conditions</MyCheckbox>
<MyCheckbox value="privacy" isRequired>Privacy policy</MyCheckbox>
<MyCheckbox value="cookies" isRequired>Cookie policy</MyCheckbox>
<FieldError />
</CheckboxGroup>
<Button type="submit">Submit</Button>
</Form>
The description slot can be used to associate additional help text with a checkbox group.
<CheckboxGroup>
<Label>Pets</Label>
<MyCheckbox value="dogs">Dogs</MyCheckbox>
<MyCheckbox value="cats">Cats</MyCheckbox>
<MyCheckbox value="dragons">Dragons</MyCheckbox>
<Text slot="description">Select your pets.</Text>
</CheckboxGroup>
.react-aria-CheckboxGroup {
[slot=description] {
font-size: 12px;
}
}
The entire CheckboxGroup can be disabled with the isDisabled prop.
<MyCheckboxGroup label="Favorite sports" isDisabled>
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball">Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>
To disable an individual checkbox, pass isDisabled to the Checkbox instead.
<MyCheckboxGroup label="Favorite sports">
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball" isDisabled>Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>
The isReadOnly prop makes the selection immutable. Unlike isDisabled, the CheckboxGroup remains focusable.
See the MDN docs for more information.
<MyCheckboxGroup label="Favorite sports" defaultValue={['baseball']} isReadOnly>
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball">Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>
Within a <CheckboxGroup>, most <Checkbox> props are set automatically. The value prop is required to identify the checkbox within the group.
<Text> accepts all HTML attributes.
A <FieldError> displays validation errors.
React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin className attribute which can be targeted using CSS selectors. These follow the react-aria-ComponentName naming convention.
.react-aria-CheckboxGroup {
/* ... */
}
A custom className can also be specified on any component. This overrides the default className provided by React Aria with your own.
<Checkbox className="my-checkbox">
</Checkbox>
In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:
.react-aria-Checkbox[data-selected] {
/* ... */
}
The className and style props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like Tailwind.
<Checkbox className={({isPressed}) => isPressed ? 'bg-gray-700' : 'bg-gray-600'} />
Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could render an extra element when the checkbox is selected.
<Checkbox>
{({isSelected}) => (
<>
{isSelected && <CheckIcon />}
Subscribe
</>
)}
</Checkbox>
The states and selectors for each component used in a CheckboxGroup are documented below.
A CheckboxGroup can be targeted with the .react-aria-CheckboxGroup CSS selector, or by overriding with a custom className. It supports the following states and render props:
A Checkbox can be targeted with the .react-aria-Checkbox CSS selector, or by overriding with a custom className. It supports the following states:
The help text elements within a CheckboxGroup can be targeted with the [slot=description] and [slot=errorMessage] CSS selectors, or by adding a custom className.
A FieldError can be targeted with the .react-aria-FieldError CSS selector, or by overriding with a custom className. It supports the following render props:
All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in mergeProps).
The components in a CheckboxGroup support the following contexts:
<ContextTable components={['CheckboxGroup', 'Checkbox']} docs={docs} />
This example shows a CheckboxDescription component that accepts a checkbox in its children and renders a description element below it. It uses the useId hook to generate a unique id for the description, and associates it with the checkbox via the aria-describedby attribute passed to the CheckboxContext provider.
import {CheckboxContext} from 'react-aria-components';
import {useId} from 'react-aria';
interface CheckboxDescriptionProps {
children?: React.ReactNode,
description?: string
}
function CheckboxDescription({children, description}: CheckboxDescriptionProps) {
let descriptionId = useId();
return (
<div>
<CheckboxContext.Provider value={{'aria-describedby': descriptionId}}>
{children}
</CheckboxContext.Provider>
<small id={descriptionId}>{description}</small>
</div>
);
}
<MyCheckboxGroup label="Email settings" defaultValue={['newsletter', 'deals', 'notifications']}>
<CheckboxDescription description="Receive our newsletter once per week.">
<MyCheckbox value="newsletter">Newsletter</MyCheckbox>
</CheckboxDescription>
<CheckboxDescription description="The best deals and sales for members.">
<MyCheckbox value="deals">Deals</MyCheckbox>
</CheckboxDescription>
<CheckboxDescription description="Notifications about your orders.">
<MyCheckbox value="notifications">Notifications</MyCheckbox>
</CheckboxDescription>
</MyCheckboxGroup>
CheckboxGroup passes props to its child components, such as the label, via their associated contexts. These contexts are exported so you can also consume them in your own custom components. This enables you to reuse existing components from your app or component library together with React Aria Components.
<ContextTable components={['Label', 'Text']} docs={docs} />
This example consumes from LabelContext in an existing styled label component to make it compatible with React Aria Components. The <TypeLink links={docs.links} type={docs.exports.useContextProps} /> hook merges the local props and ref with the ones provided via context by CheckboxGroup.
import type {LabelProps} from 'react-aria-components';
import {LabelContext, useContextProps} from 'react-aria-components';
const MyCustomLabel = React.forwardRef((props: LabelProps, ref: React.ForwardedRef<HTMLLabelElement>) => {
// Merge the local props and ref with the ones provided via context.
///- begin highlight -///
[props, ref] = useContextProps(props, ref, LabelContext);
///- end highlight -///
// ... your existing Label component
return <label {...props} ref={ref} />;
});
Now you can use MyCustomLabel within a CheckboxGroup, in place of the builtin React Aria Components Label.
<CheckboxGroup>
<MyCustomLabel>Favorite sports</MyCustomLabel>
<MyCheckbox value="soccer">Soccer</MyCheckbox>
<MyCheckbox value="baseball">Baseball</MyCheckbox>
<MyCheckbox value="basketball">Basketball</MyCheckbox>
</CheckboxGroup>
CheckboxGroup provides a <TypeLink links={statelyDocs.links} type={statelyDocs.exports.CheckboxGroupState} /> object to its children via CheckboxGroupStateContext. This can be used to access and manipulate the checkbox group's state.
This example shows a SelectionCount component that can be placed within a CheckboxGroup to display the number of selected items.
import {CheckboxGroupStateContext} from 'react-aria-components';
function SelectionCount() {
/*- begin highlight -*/
let state = React.useContext(CheckboxGroupStateContext)!;
/*- end highlight -*/
return <small>{state.value.length} items selected.</small>;
}
<MyCheckboxGroup label="Sandwich condiments">
<MyCheckbox value="lettuce">Lettuce</MyCheckbox>
<MyCheckbox value="tomato">Tomato</MyCheckbox>
<MyCheckbox value="onion">Onion</MyCheckbox>
<MyCheckbox value="sprouts">Sprouts</MyCheckbox>
<SelectionCount />
</MyCheckboxGroup>
If you need to customize things further, such as accessing internal state or customizing DOM structure, you can drop down to the lower level Hook-based API. See useCheckboxGroup for more details.