Toggle
This is a headless button with two states. You can control the selected state, or you can let the component control it. The component has native button semantics and modality-aware data attributes for the styles.
Anatomy
Toggle.Root is the only part. It makes a native <button type="button"> element with aria-pressed. Its children can be a snippet that receives the current render state.
<script>
import { Toggle } from '@human-kit/ui';
</script>
<Toggle.Root defaultSelected aria-label="Favorite">Favorite</Toggle.Root>Standalone buttons
The component shows each visual state in data-* attributes: data-selected, data-pressed, data-hovered, data-focus-visible, and data-disabled. Thus you write all of the styles in plain CSS or in utility classes. Use defaultSelected when the component controls the state.
Controlled state
Bind selected when your own code controls the toggle. Use onChange to react when the user changes the state.
Usage guidelines
- Use
selectedanddefaultSelectedfor the state of the toggle. - If you control or bind the state,
selected={undefined}becomesfalse. To usedefaultSelected, do not give aselectedprop. - Use
onChangeto react when the user changes the state. - Use
valueas a stable identifier inside aToggleGroup. The component putsvalueon the button, butvaluedoes not show the selected state. - A toggle with only an icon must have an accessible name. Give it an
aria-labelor anaria-labelledbyattribute. - If the label changes with the state, keep the accessible name the same. Let
aria-pressedannounce the state.
Accessibility
Toggle.Rootmakes a native<button type="button">element.- The component gives the selected state to assistive technology with
aria-pressed="true" | "false". - The
Enterkey and theSpacekey activate the button, like a native button. data-focus-visibleobeys the shared modality contract. The component shows it only for a keyboard focus or a virtual focus.
API reference
Root
The toggle button. It makes a native <button type="button"> element with aria-pressed. It shows its selected state and its interaction state in data attributes.
* required. Native HTML attributes of the underlying element are also accepted.