# Switch

On/off toggle built on a native checkbox with role switch, no JavaScript needed in Blade.

- Category: Form
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/switch.json
- CLI: `npx markasui@latest add switch`

## When to use

Settings that apply immediately without a save button, such as notifications or data saver mode.

- Use Checkbox when the change only applies after the form is submitted
- The label describes what gets turned on, not the current state

## Code

### Blade

Save at `resources/views/components/markas/switch.blade.php`. No extra dependencies.

```blade
@props([
    'label' => null,
])

@php
    $root = 'flex items-center gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50';
    $control = 'relative inline-flex shrink-0';
    $track = 'peer h-6 w-10 shrink-0 cursor-pointer appearance-none rounded-full bg-faint transition-colors duration-150 ease-out checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none';
    $thumb = 'pointer-events-none absolute top-0.5 left-0.5 size-5 rounded-full bg-surface transition-transform duration-150 ease-out peer-checked:translate-x-4 motion-reduce:transition-none';
    $labelClass = 'text-sm font-medium text-ink';

    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-switch|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|'.$attributes->get('value').'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $id = $attributes->get('id') ?? 'markas-switch-'.hash('xxh32', $idKey.$idIndex);
@endphp

<div class="{{ $root }}">
    <span class="{{ $control }}">
        <input type="checkbox" role="switch" {{ $attributes->merge(['id' => $id])->class([$track]) }} />
        <span class="{{ $thumb }}" aria-hidden="true"></span>
    </span>
    @if ($label)
        <label for="{{ $id }}" class="{{ $labelClass }}">{{ $label }}</label>
    @endif
</div>
```

```blade
<x-markas.switch name="notifications" label="Email notifications" :checked="$user->wants_email" />
```

No Alpine.js needed.

### React

Save at `src/components/markas/Switch.tsx`. No extra dependencies.

```tsx
"use client";

import {
  useId,
  type ChangeEvent,
  type ComponentProps,
  type ReactNode,
} from "react";

const root =
  "flex items-center gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative inline-flex shrink-0";
const track =
  "peer h-6 w-10 shrink-0 cursor-pointer appearance-none rounded-full bg-faint transition-colors duration-150 ease-out checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const thumb =
  "pointer-events-none absolute top-0.5 left-0.5 size-5 rounded-full bg-surface transition-transform duration-150 ease-out peer-checked:translate-x-4 motion-reduce:transition-none";
const labelClass = "text-sm font-medium text-ink";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

export type SwitchProps = Omit<ComponentProps<"input">, "type" | "role"> & {
  label?: ReactNode;
  onCheckedChange?: (checked: boolean) => void;
};

export function Switch({
  label,
  id,
  className,
  onChange,
  onCheckedChange,
  ...props
}: SwitchProps) {
  const generatedId = useId();
  const switchId = id ?? generatedId;
  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    onChange?.(event);
    onCheckedChange?.(event.currentTarget.checked);
  };

  return (
    <div className={root}>
      <span className={control}>
        <input
          id={switchId}
          className={cx(track, className)}
          onChange={handleChange}
          {...props}
          type="checkbox"
          role="switch"
        />
        <span className={thumb} aria-hidden="true" />
      </span>
      {label && (
        <label htmlFor={switchId} className={labelClass}>
          {label}
        </label>
      )}
    </div>
  );
}
```

```tsx
import { Switch } from "@/components/markas/Switch";

<Switch
  name="notifications"
  label="Email notifications"
  defaultChecked
  onCheckedChange={(checked) => console.log(checked)}
/>;
```

### Vue

Save at `src/components/markas/Switch.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { computed, useId } from "vue";

defineOptions({ inheritAttrs: false });

const props = defineProps<{
  label?: string;
  id?: string;
}>();
const model = defineModel<boolean>({ default: false });

const root =
  "flex items-center gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative inline-flex shrink-0";
const track =
  "peer h-6 w-10 shrink-0 cursor-pointer appearance-none rounded-full bg-faint transition-colors duration-150 ease-out checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const thumb =
  "pointer-events-none absolute top-0.5 left-0.5 size-5 rounded-full bg-surface transition-transform duration-150 ease-out peer-checked:translate-x-4 motion-reduce:transition-none";
const labelClass = "text-sm font-medium text-ink";

const generatedId = useId();
const switchId = computed(() => props.id ?? generatedId);
</script>

<template>
  <div :class="root">
    <span :class="control">
      <input
        :id="switchId"
        v-model="model"
        :class="track"
        v-bind="$attrs"
        type="checkbox"
        role="switch"
      />
      <span :class="thumb" aria-hidden="true" />
    </span>
    <label v-if="props.label" :for="switchId" :class="labelClass">{{
      props.label
    }}</label>
  </div>
</template>
```

```vue
<script setup lang="ts">
import { ref } from "vue";
import Switch from "@/components/markas/Switch.vue";

const notifications = ref(true);
</script>

<template>
  <Switch
    v-model="notifications"
    name="notifications"
    label="Email notifications"
  />
</template>
```

### Svelte

Save at `src/lib/components/markas/Switch.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { HTMLInputAttributes } from "svelte/elements";

  const root =
    "flex items-center gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
  const control = "relative inline-flex shrink-0";
  const track =
    "peer h-6 w-10 shrink-0 cursor-pointer appearance-none rounded-full bg-faint transition-colors duration-150 ease-out checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
  const thumb =
    "pointer-events-none absolute top-0.5 left-0.5 size-5 rounded-full bg-surface transition-transform duration-150 ease-out peer-checked:translate-x-4 motion-reduce:transition-none";
  const labelClass = "text-sm font-medium text-ink";

  type Props = Omit<HTMLInputAttributes, "type" | "role"> & {
    label?: string;
    checked?: boolean;
  };

  let {
    label,
    id,
    checked = $bindable(false),
    class: className,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const switchId = $derived(id ?? generatedId);
</script>

<div class={root}>
  <span class={control}>
    <input
      id={switchId}
      bind:checked
      class={[track, className]}
      {...rest}
      type="checkbox"
      role="switch"
    />
    <span class={thumb} aria-hidden="true"></span>
  </span>
  {#if label}
    <label for={switchId} class={labelClass}>{label}</label>
  {/if}
</div>
```

```svelte
<script lang="ts">
  import Switch from "$lib/components/markas/Switch.svelte";

  let notifications = $state(true);
</script>

<Switch
  bind:checked={notifications}
  name="notifications"
  label="Email notifications"
/>
```

### Astro

Save at `src/components/markas/Switch.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root =
  "flex items-center gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative inline-flex shrink-0";
const track =
  "peer h-6 w-10 shrink-0 cursor-pointer appearance-none rounded-full bg-faint transition-colors duration-150 ease-out checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const thumb =
  "pointer-events-none absolute top-0.5 left-0.5 size-5 rounded-full bg-surface transition-transform duration-150 ease-out peer-checked:translate-x-4 motion-reduce:transition-none";
const labelClass = "text-sm font-medium text-ink";

type Props = Omit<HTMLAttributes<"input">, "type" | "role"> & {
  label?: string;
};

const { label, id, class: className, ...rest } = Astro.props;
const switchId = id ?? `markas-switch-${crypto.randomUUID().slice(0, 8)}`;
---

<div class={root}>
  <span class={control}>
    <input
      id={switchId}
      class:list={[track, className]}
      {...rest}
      type="checkbox"
      role="switch"
    />
    <span class={thumb} aria-hidden="true"></span>
  </span>
  {
    label && (
      <label for={switchId} class={labelClass}>
        {label}
      </label>
    )
  }
</div>
```

```astro
---
import Switch from "@/components/markas/Switch.astro";
---

<Switch name="notifications" label="Email notifications" checked />
```

No client script: the switch is a native checkbox.

### Angular

Save at `src/app/markas/switch.component.ts`. No extra dependencies.

```ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  linkedSignal,
  output,
} from "@angular/core";

const root =
  "flex items-center gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative inline-flex shrink-0";
const track =
  "peer h-6 w-10 shrink-0 cursor-pointer appearance-none rounded-full bg-faint transition-colors duration-150 ease-out checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const thumb =
  "pointer-events-none absolute top-0.5 left-0.5 size-5 rounded-full bg-surface transition-transform duration-150 ease-out peer-checked:translate-x-4 motion-reduce:transition-none";
const labelClass = "text-sm font-medium text-ink";

let nextId = 0;

/**
 * Host stays out of layout (display: contents). id, name, aria-label, and class move to the
 * input, so the host attributes are cleared to avoid duplicate ids and labels.
 */
@Component({
  selector: "markas-switch",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "[attr.name]": "null",
    "[attr.aria-label]": "null",
  },
  template: `
    <div [class]="root">
      <span [class]="control">
        <input
          #field
          [id]="switchId()"
          [class]="trackClass()"
          [checked]="on()"
          [disabled]="disabled()"
          [attr.name]="name() ?? null"
          [attr.aria-label]="ariaLabel() ?? null"
          type="checkbox"
          role="switch"
          (change)="toggle(field.checked)"
        />
        <span [class]="thumb" aria-hidden="true"></span>
      </span>
      @if (label()) {
        <label [for]="switchId()" [class]="labelClass">{{ label() }}</label>
      }
    </div>
  `,
})
export class Switch {
  readonly label = input<string>();
  readonly id = input<string>();
  readonly name = input<string>();
  readonly checked = input(false, { transform: booleanAttribute });
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly ariaLabel = input<string | undefined>(undefined, {
    alias: "aria-label",
  });
  readonly userClass = input("", { alias: "class" });
  /** Emits the new state; together with `checked` this enables `[(checked)]`. */
  readonly checkedChange = output<boolean>();

  protected readonly root = root;
  protected readonly control = control;
  protected readonly thumb = thumb;
  protected readonly labelClass = labelClass;
  protected readonly on = linkedSignal(() => this.checked());
  private readonly generatedId = `markas-switch-${nextId++}`;
  protected readonly switchId = computed(() => this.id() ?? this.generatedId);
  protected readonly trackClass = computed(() =>
    [track, this.userClass()].filter(Boolean).join(" "),
  );

  protected toggle(value: boolean) {
    this.on.set(value);
    this.checkedChange.emit(value);
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import { Switch } from "./markas/switch.component";

@Component({
  selector: "app-settings",
  imports: [Switch],
  template: `
    <markas-switch
      [(checked)]="notifications"
      name="notifications"
      label="Email notifications"
    />
  `,
})
export class Settings {
  readonly notifications = signal(true);
}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` | - | Label text next to the switch, linked through for/id. |
| `checked / defaultChecked / v-model / bind:checked` | `boolean` | false | On state. Blade and Astro use the checked attribute, React checked or defaultChecked, Vue v-model, Svelte bind:checked, Angular checked or [(checked)]. |
| `onCheckedChange` | `(checked: boolean) => void` | - | React only. Called with the new state every time the switch changes. |
| `checkedChange` | `output<boolean>` | - | Angular only. Emits the new state every time the switch changes. |
| `disabled` | `boolean` | false | Disables the switch and dims the label. |
| `id` | `string` | auto | Input id. Generated when empty. |

## Accessibility

- A native checkbox input with role switch, so screen readers announce on or off from the checked state.
- Space toggles the state, and clicking the label toggles it too.
- The thumb is decorative (aria-hidden) and moves through CSS peer-checked.

## Notes

- Switch is an `<input type="checkbox" role="switch">`, so its value is submitted with the form like a regular checkbox.
- The on state is announced from the native `checked`, so no `aria-checked` is needed. The look uses `checked:` and `peer-checked:`, not `data-state`.
- The component has no built-in text. Translate `label` directly.
