Component
Switch With Icon
Switch with an optional icon that communicates the setting's meaning.
- Component
- React
- TSX
- Tailwind CSS
- MIT
What it does
Capabilities
- Semantic HTML
- Native form control
- Native input + role=switch
- Associated labels
- ARIA
Preview
Live component
9:41 100%
devsnips.site/library/react/components/switches/switch-with-icon/ fluid · no fixed width 100%
Install
Add to your project
npx devsnips add React/Components/Switches/switch-with-icon React/Components/Switches/switch-with-icon import type { ChangeEvent, ReactNode } from "react";
import { useId, useState } from "react";
function cx(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(" ");
}
export interface SwitchWithIconProps {
label: ReactNode;
/** Optional icon that communicates the setting's meaning (e.g. a bell for notifications). */
icon?: ReactNode;
checked?: boolean;
defaultChecked?: boolean;
onChange?: (checked: boolean, event: ChangeEvent<HTMLInputElement>) => void;
disabled?: boolean;
required?: boolean;
invalid?: boolean;
name?: string;
value?: string | number | readonly string[];
id?: string;
"aria-describedby"?: string;
className?: string;
}
/**
* A switch with an optional leading icon that communicates meaning (e.g. a
* bell for notifications, a shield for security). Icons are ReactNode and
* must not be purely decorative — omit `icon` when none adds meaning; the
* label still carries the accessible name. Built on the native
* `<input type="checkbox" role="switch">`; the icon sits inside the
* clickable label.
*/
export function SwitchWithIcon({
label,
icon,
checked,
defaultChecked,
onChange,
disabled,
required,
invalid,
name,
value,
id,
"aria-describedby": ariaDescribedby,
className,
}: SwitchWithIconProps) {
const generatedId = useId();
const inputId = id ?? `switch-${generatedId}`;
const isControlled = checked !== undefined;
const [internal, setInternal] = useState<boolean>(defaultChecked ?? false);
const isChecked = isControlled ? checked : internal;
function handleChange(event: ChangeEvent<HTMLInputElement>) {
const next = event.target.checked;
if (!isControlled) setInternal(next);
onChange?.(next, event);
}
return (
<label
htmlFor={inputId}
className={cx(
"inline-flex items-center gap-2.5 text-sm leading-5 text-[var(--ds-color-foreground)]",
disabled ? "cursor-not-allowed" : "cursor-pointer",
className,
)}
>
<span className={cx("relative inline-flex h-[14px] w-[24px] shrink-0 items-center", disabled && "opacity-50")}>
<input
id={inputId}
type="checkbox"
role="switch"
aria-checked={isChecked}
className={cx(
"absolute inset-0 h-full w-full cursor-pointer appearance-none rounded-full border transition-colors duration-150 ease-out hover:border-[var(--ds-color-border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:cursor-not-allowed motion-reduce:transition-none",
invalid
? (isChecked
? "border-[var(--ds-color-destructive)] bg-[var(--ds-color-destructive)]"
: "border-[var(--ds-color-destructive)]")
: isChecked
? "border-[var(--ds-color-primary)] bg-[var(--ds-color-primary)]"
: "border-[var(--ds-color-border)] bg-[var(--ds-color-input)]",
)}
checked={isControlled ? isChecked : undefined}
defaultChecked={isControlled ? undefined : defaultChecked}
disabled={disabled}
required={required}
aria-invalid={invalid ? true : undefined}
aria-describedby={ariaDescribedby}
name={name}
value={value}
onChange={handleChange}
/>
<span
aria-hidden="true"
className={cx(
"pointer-events-none absolute left-[2px] top-[2px] size-[10px] rounded-full transition-[transform,background-color] duration-150 ease-out motion-reduce:transition-none",
isChecked ? "translate-x-[10px]" : "translate-x-0",
invalid && isChecked
? "bg-[var(--ds-color-destructive-foreground)]"
: isChecked
? "bg-[var(--ds-color-primary-foreground)]"
: "bg-[var(--ds-color-muted-foreground)]",
)}
/>
</span>
{icon ? (
<span
className={cx(
"inline-flex size-4 shrink-0 items-center justify-center",
isChecked ? "text-[var(--ds-color-primary)]" : "text-[var(--ds-color-muted-foreground)]",
)}
>
{icon}
</span>
) : null}
<span className="select-none">
{label}
{required ? (
<span aria-hidden="true" className="ml-0.5 text-[var(--ds-color-destructive)]">*</span>
) : null}
</span>
</label>
);
}
export default SwitchWithIcon; /* DevSnips React — JavaScript parity build.
* Same API, behavior, and classes as code.tsx; TypeScript types removed.
* Regenerated from code.tsx — edit code.tsx and re-run the generator.
*/
import { useId, useState } from "react";
function cx(...parts) {
return parts.filter(Boolean).join(" ");
}
export function SwitchWithIcon({
label,
icon,
checked,
defaultChecked,
onChange,
disabled,
required,
invalid,
name,
value,
id,
"aria-describedby": ariaDescribedby,
className
}) {
const generatedId = useId();
const inputId = id ?? `switch-${generatedId}`;
const isControlled = checked !== undefined;
const [internal, setInternal] = useState(defaultChecked ?? false);
const isChecked = isControlled ? checked : internal;
function handleChange(event) {
const next = event.target.checked;
if (!isControlled) setInternal(next);
onChange?.(next, event);
}
return <label
htmlFor={inputId}
className={cx(
"inline-flex items-center gap-2.5 text-sm leading-5 text-[var(--ds-color-foreground)]",
disabled ? "cursor-not-allowed" : "cursor-pointer",
className
)}
>
<span className={cx("relative inline-flex h-[14px] w-[24px] shrink-0 items-center", disabled && "opacity-50")}>
<input
id={inputId}
type="checkbox"
role="switch"
aria-checked={isChecked}
className={cx(
"absolute inset-0 h-full w-full cursor-pointer appearance-none rounded-full border transition-colors duration-150 ease-out hover:border-[var(--ds-color-border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ds-color-focus-ring)] disabled:cursor-not-allowed motion-reduce:transition-none",
invalid ? isChecked ? "border-[var(--ds-color-destructive)] bg-[var(--ds-color-destructive)]" : "border-[var(--ds-color-destructive)]" : isChecked ? "border-[var(--ds-color-primary)] bg-[var(--ds-color-primary)]" : "border-[var(--ds-color-border)] bg-[var(--ds-color-input)]"
)}
checked={isControlled ? isChecked : undefined}
defaultChecked={isControlled ? undefined : defaultChecked}
disabled={disabled}
required={required}
aria-invalid={invalid ? true : undefined}
aria-describedby={ariaDescribedby}
name={name}
value={value}
onChange={handleChange}
/>
<span
aria-hidden="true"
className={cx(
"pointer-events-none absolute left-[2px] top-[2px] size-[10px] rounded-full transition-[transform,background-color] duration-150 ease-out motion-reduce:transition-none",
isChecked ? "translate-x-[10px]" : "translate-x-0",
invalid && isChecked ? "bg-[var(--ds-color-destructive-foreground)]" : isChecked ? "bg-[var(--ds-color-primary-foreground)]" : "bg-[var(--ds-color-muted-foreground)]"
)}
/>
</span>
{icon ? <span
className={cx(
"inline-flex size-4 shrink-0 items-center justify-center",
isChecked ? "text-[var(--ds-color-primary)]" : "text-[var(--ds-color-muted-foreground)]"
)}
>
{icon}
</span> : null}
<span className="select-none">
{label}
{required ? <span aria-hidden="true" className="ml-0.5 text-[var(--ds-color-destructive)]">*</span> : null}
</span>
</label>;
}
export default SwitchWithIcon; # Switch With Icon
Switch with an optional icon that communicates the setting's meaning.
## Usage
```tsx
<SwitchWithIcon label="Email notifications" icon={<BellIcon />} defaultChecked />
```
## JavaScript
A `code.jsx` build is provided for projects that ship plain JSX. It exposes the same API and behavior as `code.tsx` — only the TypeScript types are removed.
```jsx
<SwitchWithIcon label="Email notifications" icon={<BellIcon />} defaultChecked />
```
## Props
| Name | Type | Default | Description |
|---|---|---:|---|
| `label` | `ReactNode` (required) | — | Visible label (omit for an icon-only / aria-label control). |
| `checked` / `defaultChecked` | `boolean` | `false` | Controlled / uncontrolled checked state. |
| `onChange` | `(checked, event) => void` | — | Change callback. |
| `disabled` | `boolean` | — | Disables the control. |
| `required` | `boolean` | — | Marks the field required (renders `*`). |
| `invalid` | `boolean` | — | Sets `aria-invalid` + destructive styling. |
| `name` / `value` | `string` | — | Native form name/value. |
| `id` | `string` | generated | Input id (also the label `htmlFor`). |
| `aria-label` / `aria-labelledby` / `aria-describedby` | `string` | — | Override association. |
| `icon` | `ReactNode` | — | Optional leading icon that communicates the setting's meaning. Omit when none adds meaning. |
## States
Same native switch as the reference, with an optional ReactNode `icon` rendered between the control and the label. The icon is state-aware (primary token when on, muted when off) but the state is never communicated by icon color alone — the thumb and track carry it.
## Accessibility
`<label htmlFor>` association; the icon is decorative-adjacent (the label still carries the accessible name). `aria-invalid` for errors, `aria-describedby` for external helper text, visible `focus-visible` ring.
## Styling
Built with React, Tailwind CSS, and DevSnips design tokens. The component consumes the `--ds-*` semantic tokens via arbitrary values (for example `bg-[var(--ds-color-primary)]`). Define the tokens once in your theme — no component-specific CSS file is required.
## Design Tokens
See [React/DESIGN_TOKENS.md](../../../DESIGN_TOKENS.md) for the authoritative token specification. This switch uses the semantic color, radius, spacing, and motion tokens.
## Notes
Icons must communicate meaning (a bell for notifications, a shield for security) — they are not decoration. Do not add icons to every switch in a dense settings page; use them where the glyph disambiguates a short label. 128 lines UTF-8 · LF · Spaces: 2
DevSnips AI ready Claude · Cursor · Windsurf
Agent skill & Model Context Protocol
Pass this component straight into your AI workflow. DevSnips exposes each resource as a structured, addressable registry entry, so your agent installs the real files instead of approximating them.
devsnips://components/switches/switch-with-icon I want to use this DevSnips resource in production: Page: https://devsnips.site/library/react/components/switches/switch-with-icon/ Install: npx devsnips add React/Components/Switches/switch-with-icon This is the Switch With Icon — Switch with an optional icon that communicates the setting's meaning. Use this DevSnips resource as the starting point for my project. Adapt it to my project's stack and conventions, fix any issues, and make it production-ready while preserving its intended design and behavior.
Paste into ChatGPT, Claude or your agent — it already carries the page URL and the exact install path.
Resource URI
devsnips://components/switches/switch-with-icon