Back to React Spectrum

CheckboxGroup

packages/react-aria-components/docs/CheckboxGroup.mdx

2022-12-1621.6 KB
Original Source

{/* 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';


category: Forms keywords: [checkbox, input, aria] type: component

CheckboxGroup

<PageDescription>{docs.exports.CheckboxGroup.description}</PageDescription>

<HeaderInfo packageData={packageData} componentNames={['CheckboxGroup']} sourceData={[ {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/'} ]} />

Example

tsx
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>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary> ```css hidden @import './Checkbox.mdx' layer(checkbox); @import './Form.mdx' layer(form); @import './Button.mdx' layer(button); ```
css
@import "@react-aria/example-theme";

.react-aria-CheckboxGroup {
  display: flex;
  flex-direction: column;
  gap: 0.571rem;
  color: var(--text-color);
}
</details>

Features

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.

  • Accessible – Checkbox groups are exposed to assistive technology via ARIA, and automatically associate a nested <Label>. Description and error message help text slots are supported as well.
  • HTML form integration – Each individual checkbox uses a visually hidden <input> element under the hood, which enables HTML form integration and autofill.
  • Validation – Support for native HTML constraint validation with customizable UI, custom validation functions, and server-side validation errors.

Anatomy

<Anatomy />

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.

tsx
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.

Concepts

CheckboxGroup makes use of the following concepts:

<section className={styles.cardGroup} data-size="small">

<ExampleCard url="forms.html" title="Forms" description="Validating and submitting form data, and integrating with form libraries.">

<Form /> </ExampleCard> </section>

Composed components

A CheckboxGroup uses the following components, which may also be used standalone or reused in other components.

<section className={styles.cardGroup} data-size="small">

<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>

Starter kits

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" />

Reusable wrappers

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.

tsx
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>

Value

Default value

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.

tsx
<MyCheckboxGroup label="Favorite sports (uncontrolled)" defaultValue={['soccer', 'baseball']}>
  <MyCheckbox value="soccer">Soccer</MyCheckbox>
  <MyCheckbox value="baseball">Baseball</MyCheckbox>
  <MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>

Controlled value

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.

tsx
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>
  );
}

HTML forms

CheckboxGroup supports the name prop, paired with the Checkbox value prop, for integration with HTML forms.

tsx
<MyCheckboxGroup label="Favorite sports" name="sports">
  <MyCheckbox value="soccer">Soccer</MyCheckbox>
  <MyCheckbox value="baseball">Baseball</MyCheckbox>
  <MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>

Validation

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.

Group validation

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.

tsx
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>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-CheckboxGroup {
  .react-aria-FieldError {
    font-size: 12px;
    color: var(--invalid-color);
  }
}
</details>

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.

Individual Checkbox validation

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.

tsx
<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>

Description

The description slot can be used to associate additional help text with a checkbox group.

tsx
<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>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-CheckboxGroup {
  [slot=description] {
    font-size: 12px;
  }
}
</details>

Disabled

The entire CheckboxGroup can be disabled with the isDisabled prop.

tsx
<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.

tsx
<MyCheckboxGroup label="Favorite sports">
  <MyCheckbox value="soccer">Soccer</MyCheckbox>
  <MyCheckbox value="baseball" isDisabled>Baseball</MyCheckbox>
  <MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>

Read only

The isReadOnly prop makes the selection immutable. Unlike isDisabled, the CheckboxGroup remains focusable. See the MDN docs for more information.

tsx
<MyCheckboxGroup label="Favorite sports" defaultValue={['baseball']} isReadOnly>
  <MyCheckbox value="soccer">Soccer</MyCheckbox>
  <MyCheckbox value="baseball">Baseball</MyCheckbox>
  <MyCheckbox value="basketball">Basketball</MyCheckbox>
</MyCheckboxGroup>

Props

CheckboxGroup

<PropTable component={docs.exports.CheckboxGroup} links={docs.links} />

Checkbox

Within a <CheckboxGroup>, most <Checkbox> props are set automatically. The value prop is required to identify the checkbox within the group.

<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary> <PropTable component={docs.exports.Checkbox} links={docs.links} /> </details>

Text

<Text> accepts all HTML attributes.

FieldError

A <FieldError> displays validation errors.

<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary> <PropTable component={docs.exports.FieldError} links={docs.links} /> </details>

Styling

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.

css
.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.

jsx
<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:

css
.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.

jsx
<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.

jsx
<Checkbox>
  {({isSelected}) => (
    <>
      {isSelected && <CheckIcon />}
      Subscribe
    </>
  )}
</Checkbox>

The states and selectors for each component used in a CheckboxGroup are documented below.

CheckboxGroup

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:

<StateTable properties={docs.exports.CheckboxGroupRenderProps.properties} />

Checkbox

A Checkbox can be targeted with the .react-aria-Checkbox CSS selector, or by overriding with a custom className. It supports the following states:

<StateTable properties={docs.exports.CheckboxRenderProps.properties} />

Text

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.

FieldError

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:

<StateTable properties={docs.exports.FieldErrorRenderProps.properties} />

Advanced customization

Contexts

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.

tsx
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>

Custom children

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.

tsx
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.

tsx
<CheckboxGroup>
  <MyCustomLabel>Favorite sports</MyCustomLabel>
  <MyCheckbox value="soccer">Soccer</MyCheckbox>
  <MyCheckbox value="baseball">Baseball</MyCheckbox>
  <MyCheckbox value="basketball">Basketball</MyCheckbox>
</CheckboxGroup>

State

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.

tsx
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>

Hooks

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.