Back to React Spectrum

Checkbox

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

2022-12-1613.7 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 typesDocs from 'docs:@react-types/shared/src/events.d.ts'; import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable} 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/checkbox-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 {StarterKits} from '@react-spectrum/docs/src/StarterKits';


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

Checkbox

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

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

Example

tsx
import {Checkbox} from 'react-aria-components';

<Checkbox>
  <div className="checkbox">
    <svg viewBox="0 0 18 18" aria-hidden="true">
      <polyline points="1 9 7 14 15 4" />
    </svg>
  </div>
  Unsubscribe
</Checkbox>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
@import "@react-aria/example-theme";

.react-aria-Checkbox {
  --selected-color: var(--highlight-background);
  --selected-color-pressed: var(--highlight-background-pressed);
  --checkmark-color: var(--highlight-foreground);

  display: flex;
  /* This is needed so the HiddenInput is positioned correctly */
  position: relative;
  align-items: center;
  gap: 0.571rem;
  font-size: 1.143rem;
  color: var(--text-color);
  forced-color-adjust: none;

  .checkbox {
    width: 1.143rem;
    height: 1.143rem;
    border: 2px solid var(--border-color);
    border-radius: 4px;
    transition: all 200ms;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  svg {
    width: 1rem;
    height: 1rem;
    fill: none;
    stroke: var(--checkmark-color);
    stroke-width: 3px;
    stroke-dasharray: 22px;
    stroke-dashoffset: 66;
    transition: all 200ms;
  }

  &[data-pressed] .checkbox {
    border-color: var(--border-color-pressed);
  }

  &[data-focus-visible] .checkbox {
    outline: 2px solid var(--focus-ring-color);
    outline-offset: 2px;
  }

  &[data-selected],
  &[data-indeterminate] {
    .checkbox {
      border-color: var(--selected-color);
      background: var(--selected-color);
    }

    &[data-pressed] .checkbox {
      border-color: var(--selected-color-pressed);
      background: var(--selected-color-pressed);
    }

    svg {
      stroke-dashoffset: 44;
    }
  }

  &[data-indeterminate] {
    & svg {
      stroke: none;
      fill: var(--checkmark-color);
    }
  }
}
</details>

Features

Checkboxes can be built with the <input> HTML element, but this can be difficult to style. Checkbox helps achieve accessible checkboxes that can be styled as needed.

  • Styleable – Hover, press, keyboard focus, selection, and indeterminate states are provided for easy styling. These states only apply when interacting with an appropriate input device, unlike CSS pseudo classes.
  • Accessible – Uses a visually hidden <input> element under the hood, which also enables HTML form integration and autofill. A label element is built-in to ensure the checkbox is usable with assistive technologies.
  • Cross-browser – Mouse, touch, keyboard, and focus interactions are normalized to ensure consistency across browsers and devices.

Anatomy

<Anatomy />

A checkbox consists of a visual selection indicator and a label. Checkboxes support three selection states: checked, unchecked, and indeterminate. Users may click or touch a checkbox to toggle the selection state, or use the <Keyboard>Tab</Keyboard> key to navigate to it and the <Keyboard>Space</Keyboard> key to toggle it.

In most cases, checkboxes should have a visual label. If the checkbox does not have a visible label, an aria-label or aria-labelledby prop must be passed instead to identify the element to assistive technology.

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

Reusable wrappers

If you will use a Checkbox 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 Checkbox and all of its children together into a single component. It also shows how to use render props to conditionally render a different indicator icon when the checkbox is in an indeterminate state.

tsx
import type {CheckboxProps} from 'react-aria-components';

export function MyCheckbox({children, ...props}: Omit<CheckboxProps, 'children'> & {children?: React.ReactNode}) {
  return (
    <Checkbox {...props}>
      {({isIndeterminate}) => <>
        <div className="checkbox">
          <svg viewBox="0 0 18 18" aria-hidden="true">
            {isIndeterminate
              ? <rect x={1} y={7.5} width={15} height={3} />
              : <polyline points="1 9 7 14 15 4" />
            }
          </svg>
        </div>
        {children}
      </>}
    </Checkbox>
  );
}

<MyCheckbox>Unsubscribe</MyCheckbox>

Value

Default value

Checkboxes are not selected by default. The defaultSelected prop can be used to set the default state.

tsx
<MyCheckbox defaultSelected>Subscribe</MyCheckbox>

Controlled value

The isSelected prop can be used to make the selected state controlled. The onChange event is fired when the user presses the checkbox, and receives the new value.

tsx
function Example() {
  let [selected, setSelection] = React.useState(false);

  return (
    <>
      <MyCheckbox isSelected={selected} onChange={setSelection}>
        Subscribe
      </MyCheckbox>
      <p>{`You are ${selected ? 'subscribed' : 'unsubscribed'}`}</p>
    </>
  );
}

Indeterminate

A Checkbox can be in an indeterminate state, controlled using the isIndeterminate prop. This overrides the appearance of the Checkbox, whether selection is controlled or uncontrolled. The Checkbox will visually remain indeterminate until the isIndeterminate prop is set to false, regardless of user interaction.

tsx
<MyCheckbox isIndeterminate>Subscribe</MyCheckbox>

HTML forms

Checkbox supports the name and value props for integration with HTML forms.

tsx
<MyCheckbox name="newsletter" value="subscribe">Subscribe</MyCheckbox>

Validation

Checkboxes can display a validation state to communicate to the user if the current value is invalid. Implement your own validation logic in your app and set the isInvalid prop accordingly.

tsx
<MyCheckbox isInvalid>I accept the terms and conditions</MyCheckbox>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-Checkbox {
  &[data-invalid] {
    .checkbox {
      --checkmark-color: var(--gray-50);
      border-color: var(--invalid-color);
    }

    &[data-pressed] .checkbox {
      border-color: var(--invalid-color-pressed);
    }

    &[data-selected],
    &[data-indeterminate] {
      .checkbox {
        background: var(--invalid-color);
      }

      &[data-pressed] .checkbox {
        background: var(--invalid-color-pressed);
      }
    }
  }
}
</details>

Disabled

Checkboxes can be disabled using the isDisabled prop.

tsx
<MyCheckbox isDisabled>Subscribe</MyCheckbox>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-Checkbox {
  &[data-disabled] {
    color: var(--text-color-disabled);

    .checkbox {
      border-color: var(--border-color-disabled);
    }
  }
}
</details>

Read only

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

tsx
<MyCheckbox isSelected isReadOnly>Agree</MyCheckbox>

Props

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

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-Checkbox {
  /* ... */
}

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-pressed] {
  /* ... */
}

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, selectors, and render props for Checkbox are documented below.

<StateTable properties={docs.exports.CheckboxRenderProps.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).

<ContextTable components={['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>
  );
}

<CheckboxDescription description="You will receive our newsletter once per week. Unsubscribe at any time.">
  <MyCheckbox defaultSelected>Subscribe</MyCheckbox>
</CheckboxDescription>

Hooks

If you need to customize things further, such as intercepting events or customizing DOM structure, you can drop down to the lower level Hook-based API. Consume from CheckboxContext in your component with <TypeLink links={docs.links} type={docs.exports.useContextProps} /> to make it compatible with other React Aria Components. See useCheckbox for more details.

tsx
import type {CheckboxProps} from 'react-aria-components';
import {CheckboxContext, useContextProps} from 'react-aria-components';
import {useToggleState} from 'react-stately';
import {useCheckbox} from 'react-aria';

const MyCheckbox = React.forwardRef((props: CheckboxProps, ref: React.ForwardedRef<HTMLInputElement>) => {
  // Merge the local props and ref with the ones provided via context.
  ///- begin highlight -///
  [props, ref] = useContextProps(props, ref, CheckboxContext);
  ///- end highlight -///

  let state = useToggleState(props);
  let {inputProps} = useCheckbox(props, state, ref);
  return <input {...inputProps} ref={ref} />;
});