Skip to content

Latest commit

 

History

History
464 lines (353 loc) · 13.8 KB

File metadata and controls

464 lines (353 loc) · 13.8 KB

{/* Copyright 2024 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/toggle'; 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 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'; import ToggleButton from '@react-spectrum/docs/pages/assets/component-illustrations/ToggleButton.svg'; import Anatomy from '@react-aria/button/docs/ToggleButtonGroupAnatomy.svg';


category: Buttons keywords: [button, toggle button, aria, form] type: component

ToggleButtonGroup

{docs.exports.ToggleButtonGroup.description}

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

Example

import {ToggleButtonGroup, ToggleButton} from 'react-aria-components';

<ToggleButtonGroup>
  <ToggleButton id="left">Left</ToggleButton>
  <ToggleButton id="center">Center</ToggleButton>
  <ToggleButton id="right">Right</ToggleButton>
</ToggleButtonGroup>
Show CSS
@import "@react-aria/example-theme";
@import './Button.mdx' layer(button);
@import './ToggleButton.mdx' layer(togglebutton);
.react-aria-ToggleButtonGroup {
  display: flex;

  > button {
    border-radius: 0;
    z-index: 1;

    &[data-disabled] {
      z-index: 0;
    }

    &[data-selected],
    &[data-focus-visible] {
      z-index: 2;
    }
  }
}

.react-aria-ToggleButtonGroup[data-orientation=horizontal] {
  flex-direction: row;

  > button {
    margin-inline-start: -1px;
    
    &:first-child {
      border-radius: 4px 0 0 4px;
      margin-inline-start: 0;
    }

    &:last-child {
      border-radius: 0 4px 4px 0;
    }
  }
}

Features

There is no built in element for toggle button groups in HTML. ToggleButtonGroup helps achieve accessible toggle button groups that can be styled as needed.

  • Accessible – Represented as an ARIA radiogroup when using single selection, or a toolbar when using multiple selection.
  • Keyboard navigation – Users can navigate between buttons with the arrow keys. Selection can be toggled using the Enter or Space keys.
  • Styleable – Hover, press, keyboard focus, and selection states are provided for easy styling.

Anatomy

A toggle button group consists of a set of toggle buttons, and coordinates the selection state between them. Users can navigate between buttons with the arrow keys in either horizontal or vertical orientations.

import {ToggleButtonGroup, ToggleButton, SelectionIndicator} from 'react-aria-components';

<ToggleButtonGroup>
  <ToggleButton>
    <SelectionIndicator />
  </ToggleButton>
</ToggleButtonGroup>

Composed Components

Selection

ToggleButtonGroup supports both single and multiple selection modes. Use defaultSelectedKeys to provide a default set of selected items (uncontrolled) and selectedKeys to set the selected items (controlled). The value of the selected keys must match the id prop of the items.

Single selection

By default, the selectionMode of a ToggleButtonGroup is "single".

<ToggleButtonGroup defaultSelectedKeys={['list']}>
  <ToggleButton id="grid">Grid view</ToggleButton>
  <ToggleButton id="list">List view</ToggleButton>
  <ToggleButton id="gallery">Gallery view</ToggleButton>
</ToggleButtonGroup>

Multiple selection

Set selectionMode prop to multiple to allow more than one selection.

<ToggleButtonGroup selectionMode="multiple">
  <ToggleButton id="bold">Bold</ToggleButton>
  <ToggleButton id="italic">Italic</ToggleButton>
  <ToggleButton id="underline">Underline</ToggleButton>
</ToggleButtonGroup>

Controlled selection

The selectedKeys prop can be used to make the selected state controlled.

import type {Key} from 'react-aria-components';

function Example() {
  let [selected, setSelected] = React.useState(new Set<Key>(['bold']));

  return (
    <>
      <ToggleButtonGroup selectionMode="multiple" selectedKeys={selected} onSelectionChange={setSelected}>
        <ToggleButton id="bold">Bold</ToggleButton>
        <ToggleButton id="italic">Italic</ToggleButton>
        <ToggleButton id="underline">Underline</ToggleButton>
      </ToggleButtonGroup>
      <p>Current selections (controlled): {[...selected].join(', ')}</p>
    </>
  );
}

Animation

Use the SelectionIndicator component to animate selection changes.

import {ToggleButtonGroup, ToggleButton, SelectionIndicator} from 'react-aria-components';

<ToggleButtonGroup
  className="segmented-control"
  defaultSelectedKeys={['day']}
  disallowEmptySelection>
  <ToggleButton id="day">
    <SelectionIndicator />
    <span>Day</span>
  </ToggleButton>
  <ToggleButton id="week">
    <SelectionIndicator />
    <span>Week</span>
  </ToggleButton>
  <ToggleButton id="month">
    <SelectionIndicator />
    <span>Month</span>
  </ToggleButton>
  <ToggleButton id="year">
    <SelectionIndicator />
    <span>Year</span>
  </ToggleButton>
</ToggleButtonGroup>
Show CSS
.segmented-control {
  display: flex;
  background: var(--gray-100);
  width: fit-content;
  padding: 2px;
  border-radius: 8px;

  .react-aria-SelectionIndicator {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
    transition-property: translate, width;
    transition-duration: 200ms;
    border-radius: 8px;
    background: var(--gray-50);
    outline: 2px solid var(--gray-600);

    @media (prefers-reduced-motion: reduce) {
      transition: none;
    }
  }

  .react-aria-ToggleButton {
    all: unset;
    color: var(--text-color);
    font-size: 1rem;
    outline: none;
    padding: 4px 16px;
    position: relative;
    z-index: 1;
    border-radius: 8px;

    span {
      display: inline-block;
      transition: scale 200ms;
    }

     &[data-pressed] span {
      scale: 0.95;
    }

    &[data-selected] {
      z-index: 0;
    }

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

Disabled

All buttons within a ToggleButtonGroup can be disabled using the isDisabled prop.

<ToggleButtonGroup isDisabled>
  <ToggleButton id="grid">Grid view</ToggleButton>
  <ToggleButton id="list">List view</ToggleButton>
  <ToggleButton id="gallery">Gallery view</ToggleButton>
</ToggleButtonGroup>

Individual items can be disabled using the isDisabled prop on each ToggleButton.

<ToggleButtonGroup>
  <ToggleButton id="grid">Grid view</ToggleButton>
  <ToggleButton id="list" isDisabled>List view</ToggleButton>
  <ToggleButton id="gallery">Gallery view</ToggleButton>
</ToggleButtonGroup>

Orientation

By default, toggle button groups are horizontally oriented. The orientation prop can be set to "vertical" to change the arrow key navigation behavior.

<ToggleButtonGroup orientation="vertical">
  <ToggleButton id="grid">Grid</ToggleButton>
  <ToggleButton id="list">List</ToggleButton>
  <ToggleButton id="gallery">Gallery</ToggleButton>
</ToggleButtonGroup>
Show CSS
.react-aria-ToggleButtonGroup[data-orientation=vertical] {
  flex-direction: column;
  width: fit-content;

  > button {
    margin-block-start: -1px;
    
    &:first-child {
      border-radius: 4px 4px 0 0;
      margin-block-start: 0;
    }

    &:last-child {
      border-radius: 0 0 4px 4px;
    }
  }
}

Accessiblity

A ToggleButtonGroup can be labeled using the aria-label or aria-labelledby props.

<ToggleButtonGroup aria-label="Text style">
  <ToggleButton id="bold">Bold</ToggleButton>
  <ToggleButton id="italic">Italic</ToggleButton>
  <ToggleButton id="underline">Underline</ToggleButton>
</ToggleButtonGroup>

Props

ToggleButtonGroup

ToggleButton

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.

.react-aria-ToggleButtonGroup {
  /* ... */
}

A custom className can also be specified on any component. This overrides the default className provided by React Aria with your own.

<ToggleButtonGroup className="my-toggle-group">
  {/* ... */}
</ToggleButtonGroup>

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-ToggleButton[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.

<ToggleButtonGroup className={({isDisabled}) => isDisabled ? 'bg-gray-100' : '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 swap an icon depending on the selection state.

<ToggleButton>
  {({isSelected}) => (
    <>
      {isSelected ? <PinnedIcon /> : <UnpinnedIcon />}
      Pin
    </>
  )}
</ToggleButton>

The states, selectors, and render props for each component used in a ToggleButtonGroup are documented below.

ToggleButtonGroup

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

ToggleButton

A ToggleButton can be targeted with the .react-aria-ToggleButton CSS selector, or by overriding with a custom className.

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={['ToggleButtonGroup', 'ToggleButton']} docs={docs} />

State

ToggleButtonGroup provides an object to its children via ToggleGroupStateContext. This can be used to access and manipulate the toggle button group's state.

This example shows a ClearButton component that can be placed within a ToggleButtonGroup to allow the user to clear the selected item.

import {ToggleGroupStateContext, Button} from 'react-aria-components';

function ClearButton() {
  /*- begin highlight -*/
  let state = React.useContext(ToggleGroupStateContext);
  /*- end highlight -*/
  return (
    <Button onPress={() => state?.setSelectedKeys(new Set())}>
      Clear
    </Button>
  );
}

<ToggleButtonGroup selectionMode="multiple" defaultSelectedKeys={['bold', 'italic']}>
  <ToggleButton id="bold">Bold</ToggleButton>
  <ToggleButton id="italic">Italic</ToggleButton>
  <ToggleButton id="underline">Underline</ToggleButton>
  {/*- begin highlight -*/}
  <ClearButton />
  {/*- end highlight -*/}
</ToggleButtonGroup>

Hooks

If you need to customize things even further, such as accessing internal state, intercepting events, or customizing the DOM structure, you can drop down to the lower level Hook-based API. See useToggleButtonGroup for more details.