BetaPublic beta — Read the release notes
Documentation

Toggle

Basic toggle example demonstrating core behavior.

Package
@solidiom/toggle
Version
0.0.1-next.0
Status
stable

Examples

import * as Toggle from "@solidiom/toggle"

;<Toggle.Root defaultPressed={false} onPressedChange={(pressed) => console.log(pressed)}>
  Bold
</Toggle.Root>

;<Toggle.Root defaultPressed={true}>Italic</Toggle.Root>

;<Toggle.Root disabled>Strikethrough</Toggle.Root>

The toggle is a two-state button with aria-pressed. Use pressed for controlled mode or defaultPressed for uncontrolled. The Root emits data-state of “on” or “off” for styling.

View source
        export function Root(props: ToggleRootProps) {
  const { value, requestChange } = createControllableValue<boolean, "press">({
    value: props.pressed,
    defaultValue: props.defaultPressed ?? false,
    onChange: (next: boolean) => props.onPressedChange?.(next),
  })

  const handleClick = () => {
    if (props.disabled) return
    requestChange(!value(), createChangeDetails("press"))
  }

  return (
    <button
      type="button"
      aria-pressed={value() ? "true" : "false"}
      aria-disabled={props.disabled ? "true" : undefined}
      onClick={handleClick}
      class={props.class}
      style={props.style}
      {...applySemanticAttrs({
        scope: "toggle",
        part: "root",
        state: value() ? "on" : "off",
        disabled: props.disabled,
      })}
    >
      {props.children}
    </button>
  )
}