Toggle

Toggles are a two-state button that can either be off (not pressed) or on (pressed).

Give FeedbackWAI-ARIABundle Size

Installation

Base UI components are all available as a single package.

npm install @base-ui-components/react

Once you have the package installed, import the component.

import { Toggle } from '@base-ui-components/react/toggle';

Anatomy

Toggle is a single component that renders a <button>:

<Toggle>Toggle bookmark</Toggle>

Controlled

Use the pressed and onPressedChange props to control the pressed state:

const [pressed, setPressed] = React.useState(false);

<Toggle pressed={pressed} onPressedChange={setPressed}>
  {/* children */}
</Toggle>;

Uncontrolled

Use the defaultPressed prop to set the initial pressed state of the component when uncontrolled:

<Toggle defaultPressed={false}>{/* children */}</Toggle>

Accessibility

Toggles must be given an accessible name with aria-label or aria-labelledby. It is important that the label does not change based on the pressed state to ensure a smooth screen-reader experience, since announcing the pressed state is already handled by aria-pressed.

Styling

Use the [data-pressed] attribute to apply styles based on the pressed state:

<Toggle className="MyToggle">{/* children */}</Toggle>
/* base state, not pressed */
.MyToggle {
  background: white;
  color: black;
}

/* pressed state */
.MyToggle[data-pressed] {
  background: black;
  color: white;
}

API Reference

ToggleRoot

PropTypeDefaultDescription
aria-labelstringThe label for the Toggle.
aria-labelledbystringAn id or space-separated list of ids of elements that label the Toggle.
classNameunionClass names applied to the element or a function that returns them based on the component's state.
defaultPressedboolfalseThe default pressed state. Use when the component is not controlled.
disabledboolfalseIf true, the component is disabled.
onPressedChangefuncCallback fired when the pressed state is changed.
pressedboolIf true, the component is pressed.
renderunionA function to customize rendering of the component.
valuestringA unique string that identifies the component when used inside a ToggleGroup

Contents