Switch
controlsGratisMITEn tænd/sluk-kontakt, hvor knappen strækker sig, når man trykker, og glider over.
npx shadcn@latest add https://mikkelmanniche.dk/lab/r/switch.jsonPreview
Forhåndsvisningen kunne ikke hentes.
Live demo i det mørke tema.
Kode
Installér
npx shadcn@latest add https://mikkelmanniche.dk/lab/r/switch.jsonMed registret tilføjet (components.json)
npx shadcn@latest add @manniche/switchBrug
switch-demo.tsx
import { Switch } from '@/components/switch'
export default function SwitchDemo() {
return (
<div className="flex flex-col items-start gap-4">
<Switch label="Email me when an order comes in" defaultChecked />
<Switch label="Show prices with VAT" />
</div>
)
}Kilde
switch.tsx
import { MotionConfig, motion } from 'motion/react'
import { useId, useState } from 'react'
import { cn } from '@/lib/utils'
type SwitchBaseProps = {
/** Controlled state. */
checked?: boolean
/** Starting state when the switch is not controlled. */
defaultChecked?: boolean
/** Called with the new state each time the switch is flipped. */
onChange?: (checked: boolean) => void
/** Turns the switch off for pointer and keyboard. */
disabled?: boolean
/** Classes for the outer span that wraps the switch and its label. */
className?: string
}
/** The switch always has a name: pass a visible `label`, or an `aria-label` when there is no room for one. */
export type SwitchProps = SwitchBaseProps &
(
| {
/** Visible label, linked to the switch. Pass this, `aria-label` or both. */
label: string
/** Spoken name for screen readers. Required without a label; with one, it replaces the label when read aloud. */
'aria-label'?: string
}
| {
label?: undefined
/** Spoken name for a switch without a visible label. */
'aria-label': string
}
)
/** A switch whose knob stretches as you press it and springs across, like the one on a phone. */
export function Switch({ checked, defaultChecked = false, onChange, label, disabled, className, ...aria }: SwitchProps) {
const [own, setOwn] = useState(defaultChecked)
const on = checked ?? own
const id = useId()
const flip = () => {
setOwn(!on)
onChange?.(!on)
}
return (
<MotionConfig reducedMotion="user">
<span className={cn('inline-flex items-center gap-3', className)}>
<motion.button
id={id}
type="button"
role="switch"
aria-checked={on}
aria-label={aria['aria-label']}
disabled={disabled}
onClick={flip}
whileTap="pressed"
className={cn(
'relative flex h-8 after:inset-x-0 after:-inset-y-1.5 after:absolute after:content-[""] w-[52px] shrink-0 items-center rounded-full p-[3px] transition-colors duration-200 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-40',
on ? 'justify-end bg-emerald-500' : 'justify-start bg-muted',
)}
>
<motion.span
layout
// Pressed, the knob stretches towards the side it is about to move to.
variants={{ pressed: { scaleX: 1.2 } }}
style={{ originX: on ? 1 : 0 }}
transition={{ type: 'spring', stiffness: 520, damping: 46 }}
className="block h-[26px] w-[26px] rounded-full bg-white shadow-[0_2px_6px_rgb(0_0_0/0.18),0_0_0_0.5px_rgb(0_0_0/0.06)]"
/>
</motion.button>
{label && (
<label htmlFor={id} className="text-sm font-medium select-none">
{label}
</label>
)}
</span>
</MotionConfig>
)
}Props
SwitchProps
| Prop | Type | Standard | Hvad den gør |
|---|---|---|---|
checked | boolean | – | Controlled state. |
defaultChecked | boolean | false | Starting state when the switch is not controlled. |
onChange | (checked: boolean) => void | – | Called with the new state each time the switch is flipped. |
disabled | boolean | – | Turns the switch off for pointer and keyboard. |
className | string | – | Classes for the outer span that wraps the switch and its label. |
label | string | – | Visible label, linked to the switch. Pass this, aria-label or both. |
aria-label | string | – | Spoken name for screen readers. Required without a label; with one, it replaces the label when read aloud. |
A11y
Tastatur
It is a native button with role switch, so Tab focuses it and Space or Enter flips it. It shows a focus ring and respects disabled.
Skærmlæser
The button sets aria-checked. The props type requires a name: either a visible label (a real label element tied to the button id) or an aria-label.
Mindre bevægelse
The component is wrapped in MotionConfig with reducedMotion set to user, so Motion follows the system setting for the knob.