opensourceui
GitHubTwitter/X
  1. Home
  2. Components
  3. Inputs
  4. Switch Field Input
Back to Inputs

Components / Inputs

Switch Field Input

Free Inputs React component — SwitchFieldInput. MIT licensed, copy-paste ready for Next.js and Tailwind CSS.

Toggle switch with role=switch, keyboard support, hidden input for forms, and label/hint/error layout.

Preview

Email notifications

Receive product updates and release notes.

Setup

How to use

Free for personal and commercial use. No UI attribution required. Include the MIT copyright notice when copying component source into your project. Read the MIT license.

  1. 1

    Run in your terminal:

    $npm install clsx tailwind-merge lucide-react
  2. 2

    Copy lib/cn.ts below. Skip if you already have cn().

  3. 3

    Copy the code below and create components/inputs/switch-field-input.tsx in your project.

  4. 4

    Import and render:

    Example

    import { SwitchFieldInput } from "@/components/inputs/switch-field-input";

    <SwitchFieldInput label="Dark mode" checked={enabled} onCheckedChange={setEnabled} name="dark-mode" />

lib/cn.ts

1
2
3
4
5
6
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
 
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

components/inputs/switch-field-input.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"use client";
 
import {
forwardRef,
useCallback,
useId,
useState,
type ComponentPropsWithoutRef,
type KeyboardEvent,
} from "react";
 
import { cn } from "@/lib/cn";
 
export type SwitchFieldInputProps = Readonly<
{
label?: string;
hint?: string;
error?: boolean;
errorMessage?: string;
containerClassName?: string;
onCheckedChange?: (checked: boolean) => void;
} & Omit<
ComponentPropsWithoutRef<"button">,
"size" | "type" | "role" | "onChange" | "defaultChecked"
>
> & {
checked?: boolean;
defaultChecked?: boolean;
disabled?: boolean;
required?: boolean;
name?: string;
};
 
export const SwitchFieldInput = forwardRef<
HTMLButtonElement,
SwitchFieldInputProps
>(function SwitchFieldInput(
{
className,
containerClassName,
id,
label = "Email notifications",
hint = "Receive product updates and release notes.",
error = false,
errorMessage = "This setting is required.",
disabled = false,
required,
checked,
defaultChecked = false,
name,
onCheckedChange,
onClick,
onKeyDown,
...props
},
ref,
) {
const generatedId = useId();
const switchId = id ?? generatedId;
const hintId = `${switchId}-hint`;
const errorId = `${switchId}-error`;
 
const isControlled = checked !== undefined;
const [internal, setInternal] = useState(defaultChecked);
const isOn = isControlled ? checked : internal;
 
const toggle = useCallback(() => {
if (disabled) return;
const next = !isOn;
if (!isControlled) setInternal(next);
onCheckedChange?.(next);
}, [disabled, isControlled, isOn, onCheckedChange]);
 
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLButtonElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented || disabled) return;
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
toggle();
}
},
[disabled, onKeyDown, toggle],
);
 
return (
<div
data-slot="switch-field-input"
data-error={error || undefined}
data-checked={isOn || undefined}
className={cn("w-full max-w-sm font-sans", containerClassName)}
>
{name || required ? (
<input
type="checkbox"
name={name}
value="on"
checked={isOn}
required={required}
disabled={disabled}
tabIndex={-1}
aria-hidden
onChange={() => undefined}
onInvalid={(event) => {
event.preventDefault();
event.currentTarget.parentElement
?.querySelector<HTMLButtonElement>('[role="switch"]')
?.focus();
}}
className="sr-only"
/>
) : null}
 
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<p
id={`${switchId}-label`}
className="text-sm font-medium text-neutral-900"
>
{label}
{required ? (
<span className="ml-0.5 text-rose-500" aria-hidden>
*
</span>
) : null}
</p>
{hint ? (
<p id={hintId} className="mt-0.5 text-xs text-neutral-500">
{hint}
</p>
) : null}
</div>
 
<button
ref={ref}
id={switchId}
type="button"
role="switch"
disabled={disabled}
aria-checked={isOn}
aria-required={required || undefined}
aria-invalid={error || undefined}
aria-labelledby={`${switchId}-label`}
aria-describedby={
error ? errorId : hint ? hintId : undefined
}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) toggle();
}}
onKeyDown={handleKeyDown}
className={cn(
"relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 transition-[background-color,border-color] duration-200 outline-none ring-0 focus:ring-0 disabled:cursor-not-allowed disabled:opacity-50",
isOn
? "border-neutral-900 bg-neutral-900"
: "border-neutral-200 bg-neutral-100",
error && !isOn && "border-rose-300 bg-rose-50",
className,
)}
{...props}
>
<span
aria-hidden
className={cn(
"pointer-events-none absolute top-0.5 left-0.5 size-4 rounded-full bg-white transition-transform duration-200",
isOn && "translate-x-5",
)}
/>
</button>
</div>
 
{error ? (
<p id={errorId} role="alert" className="mt-1.5 text-xs text-rose-600">
{errorMessage}
</p>
) : null}
</div>
);
});
 
SwitchFieldInput.displayName = "SwitchFieldInput";
PreviousNext

On this

page

Jump to a section on this page.

  • lib/cn.ts
  • components/inputs/switch-field-input.tsx

Sponsor spot · demo preview

Logo

Your brand name

Your tagline or category

A short pitch about your product or service goes here. This is a preview of how sponsor cards will look in this sidebar.

Your call to action

This slot is available. Sponsor Opensource UI and reach developers browsing components every day.