Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/switch.ts
    import type { Html } from "@effect/ui/html"
    import { Switch as KitSwitch, type SwitchProps } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    const sizes = {
      sm: { root: "h-3.5 w-6.5", thumb: "size-2.5 data-[checked]:translate-x-3" },
      default: { root: "h-4.5 w-8", thumb: "size-3.5 data-[checked]:translate-x-3.5" },
      lg: { root: "h-6 w-10.5 p-[3px]", thumb: "size-4.5 data-[checked]:translate-x-4.5" }
    } as const
    
    export type SwitchSize = keyof typeof sizes
    
    /**
     * The kit's Switch, drawn: a track with its thumb. Pass the value as
     * `props.checked` and store what `onToggle` reports. It returns the root
     * button, so chain an `id` or `aria-label` on it, or wrap it in a label.
     */
    export const Switch = <Msg>(
      h: Html.H<Msg>,
      options: {
        readonly size?: SwitchSize | undefined
        readonly class?: string | undefined
        readonly props: SwitchProps
        readonly onToggle?: ((event: { readonly checked: boolean }) => NoInfer<Msg> | undefined) | undefined
      }
    ) => {
      const size = sizes[options.size ?? "default"]
      return KitSwitch(h, {
        props: options.props,
        onToggle: options.onToggle,
        view: (parts) =>
          parts
            .root(
              h.button.class(cn(
                "inline-flex shrink-0 items-center rounded-full border-0 bg-input p-0.5 transition-colors duration-150 " +
                  "data-[checked]:bg-brand data-[readonly]:cursor-default " +
                  "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
                size.root,
                options.class
              ))
            )
            .children(
              parts.thumb(
                h.span.class(cn(
                  "rounded-full bg-background shadow-sm transition-[translate,background-color] duration-150 " +
                    "dark:bg-foreground data-[checked]:bg-brand-foreground dark:data-[checked]:bg-brand-foreground",
                  size.thumb
                ))
              )
            )
      })
    }
    
    /** A label for the switch: around it, or beside it with `for`. It dims with a disabled switch inside it. */
    export const SwitchLabel = <Msg>(h: Html.H<Msg>, options: { readonly class?: string | undefined } = {}) =>
      h.label.class(cn(
        "inline-flex cursor-pointer items-center gap-2.5 text-[13px] leading-4.5 font-medium select-none " +
          "has-[[data-disabled]]:cursor-not-allowed has-[[data-disabled]]:text-muted-foreground",
        options.class
      ))
    
  3. Import it

    import { Switch, SwitchLabel } from "#ui/switch"
    

Usage

Basic.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Switch, SwitchLabel } from "#ui/switch"

const SwitchBasicMessage = UiSchema.TaggedEnum({ ToggledAirplaneMode: { checked: Schema.Boolean } })

export const SwitchBasic = Html.component({
  name: "SwitchBasic",
  model: Schema.Struct({ airplaneMode: Schema.Boolean }),
  message: SwitchBasicMessage
}).make({
  init: () => ({ airplaneMode: false }),
  update: {
    ToggledAirplaneMode: ($, { checked }) => $.evolve({ airplaneMode: checked })
  },
  view: (h, model) =>
    SwitchLabel(h).children(
      Switch(h, {
        props: { checked: model.airplaneMode },
        onToggle: ({ checked }) => SwitchBasicMessage.ToggledAirplaneMode({ checked })
      }),
      "Airplane mode"
    )
})

Examples

Sizes

Small, default and large, set with data-size on the root.

Settings list

Each row has a label and a description, with the switch on the right.

When someone mentions you in a comment.

A summary of your team's activity, every Monday.

New features and the occasional announcement.

Disabled and read-only

A disabled switch leaves the tab order. A read-only one keeps focus and ignores clicks.

Toggled 0 times

Card

The whole card is the label, and its text follows parts.checked.

In a form

A switch with a name submits its value through a hidden input.

Nothing submitted yet

Anatomy

The parts the view closure receives. Apply each one to an element of your own.

PartDescription
rootThe <button role="switch">. It adds the hidden input that carries the form value.
thumbA <span> inside the root.
checked, disabled, readOnly, requiredThe state as booleans, for markup that depends on it.

API reference

Props

PropTypeDescription
checkedbooleanWhether the switch is on. Required.
disabledbooleanSets the native disabled attribute: skipped by Tab, ignores clicks.
readOnlybooleanIgnores clicks but stays focusable.
requiredbooleanSets aria-required and data-required. It doesn't block a submit.
namestringThe form field's name. Without it nothing is submitted.
valuestringWhat an on switch submits, "on" by default.
uncheckedValuestringWhat an off switch submits. Nothing when unset.

Events

EventDescription
onToggle({ checked }) => message: the value the user asked for. Store it and pass it back as checked.

Data attributes

AttributeDescription
data-checkedOn root and thumb while on.
data-uncheckedOn root and thumb while off.
data-disabledOn root and thumb while disabled.
data-readonlyOn root and thumb while read-only.
data-requiredOn root and thumb while required.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.