Kobalte.v0.12.5

Toggle Button

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

Import

ts
import { ToggleButton } from "@kobalte/core";
ts
import { ToggleButton } from "@kobalte/core";

Features

  • Native HTML <button>, <a>, and custom element type support.
  • Exposed as a toggle button via the WAI ARIA Button design pattern.
  • Mouse and touch event handling, and press state management.
  • Keyboard event support for Space and Enter keys.
  • Can be controlled or uncontrolled.

Anatomy

The toggle button consists of:

  • ToggleButton.Root: the root container for a toggle button.
tsx
<ToggleButton.Root />
tsx
<ToggleButton.Root />

Example

Usage

Default pressed

An initial, uncontrolled value can be provided using the defaultPressed prop.

tsx
<ToggleButton.Root defaultPressed>...</ToggleButton.Root>
tsx
<ToggleButton.Root defaultPressed>...</ToggleButton.Root>

Controlled pressed

The pressed prop can be used to make the pressed state controlled. The onChange event is fired when the user toggle the button, and receives the new value.

The microphone is active.

tsx
import { createSignal } from "solid-js";
function ControlledExample() {
const [pressed, setPressed] = createSignal(false);
return (
<>
<ToggleButton.Root pressed={pressed()} onChange={setPressed}>
...
</ToggleButton.Root>
<p>The microphone is {pressed() ? "muted" : "active"}.</p>
</>
);
}
tsx
import { createSignal } from "solid-js";
function ControlledExample() {
const [pressed, setPressed] = createSignal(false);
return (
<>
<ToggleButton.Root pressed={pressed()} onChange={setPressed}>
...
</ToggleButton.Root>
<p>The microphone is {pressed() ? "muted" : "active"}.</p>
</>
);
}

API Reference

ToggleButton.Root

ToggleButton.Root consists of Button.Root and additional props.

PropDescription
pressedboolean
The controlled pressed state of the toggle button.
defaultPressedboolean
The default pressed state when initially rendered. Useful when you do not need to control the pressed state.
onChange(pressed: boolean) => void
Event handler called when the pressed state of the toggle button changes.
childrenJSX.Element | (state: ToggleButtonState) => JSX.Element
The children of the toggle button. Can be a JSX.Element or a render prop for having access to the internal state.
Render PropDescription
pressedAccessor<boolean>
Whether the toggle button is on (pressed) or off (not pressed).
Data attributeDescription
data-pressedPresent when the toggle button is on (pressed).

Rendered elements

ComponentDefault rendered element
ToggleButton.Rootbutton

Accessibility

Keyboard Interactions

KeyDescription
SpaceActivates/deactivates the toggle button.
EnterActivates/deactivates the toggle button.