BetaPublic beta — Read the release notes
Documentation

Toggle Group

Basic toggle group example demonstrating core behavior.

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

Examples

import * as ToggleGroup from "@solidiom/toggle-group"

;<ToggleGroup.Root
  type="single"
  defaultValue={["bold"]}
  onValueChange={(values) => console.log(values)}
>
  <ToggleGroup.Item value="bold">B</ToggleGroup.Item>
  <ToggleGroup.Item value="italic">I</ToggleGroup.Item>
  <ToggleGroup.Item value="underline">U</ToggleGroup.Item>
</ToggleGroup.Root>

Multiple selection

;<ToggleGroup.Root
  type="multiple"
  defaultValue={["bold", "italic"]}
  onValueChange={(values) => console.log(values)}
>
  <ToggleGroup.Item value="bold">B</ToggleGroup.Item>
  <ToggleGroup.Item value="italic">I</ToggleGroup.Item>
  <ToggleGroup.Item value="underline">U</ToggleGroup.Item>
</ToggleGroup.Root>

In single mode, only one item can be active at a time. In multiple mode, items toggle independently. Use the orientation prop for vertical layout.

View source
        export function Root(props: ToggleGroupRootProps) {
  const type = () => props.type ?? "single"
  const orientation = () => props.orientation ?? "horizontal"

  const { value, requestChange } = createControllableValue<string[], "toggle">({
    value: props.value,
    defaultValue: props.defaultValue ?? [],
    onChange: (next: string[]) => props.onValueChange?.(next),
    equals: (a: string[], b: string[]) => a.length === b.length && a.every((v, i) => v === b[i]),
  })

  const toggle = (itemValue: string) => {
    if (props.disabled) return
    const current = value()

    let next: string[]
    if (type() === "single") {
      next = current.includes(itemValue) ? [] : [itemValue]
    } else {
      next = current.includes(itemValue)
        ? current.filter((v: string) => v !== itemValue)
        : [...current, itemValue]
    }

    requestChange(next, createChangeDetails("toggle"))
  }

  return (
    <ToggleGroupContext
      value={{
        value,
        toggle,
        type: type(),
        disabled: props.disabled,
        orientation: orientation(),
      }}
    >
      <div
        role="group"
        aria-disabled={props.disabled ? "true" : undefined}
        class={props.class}
        style={props.style}
        {...applySemanticAttrs({
          scope: "toggle-group",
          part: "root",
          orientation: orientation(),
          disabled: props.disabled,
        })}
      >
        {props.children}
      </div>
    </ToggleGroupContext>
  )
}