Switch
The switch turns the setting on or off.
When to use
Switch turns on or off a setting that applies immediately: notifications, automatic updates, or feature access. The caption explains what will be included; its meaning is preserved in both states. For selections confirmed by submitting a form, Checkbox is usually appropriate.
The switch must have an accessible name: associated label or aria-label. The text and icons inside can explain the status, but do not replace the name of the setting. Switch reports state through a native button with the switch role and aria-checked.
Switch CSS Prefixes show global ConfigProvider.prefixCls and local prefixCls without resetting state. The prefix changes the root, handle, captions and loading. The bind:checked state, the keyboard and the native form field are preserved.
Status and binding
Switch state is boolean. Select one control method:
| Problem | Setting | Example |
|---|---|---|
| Store state in Svelte | bind:checked |
State binding |
| Set only the initial state | defaultChecked and onChange |
Basic switch |
| Link state to Form model | checked and onCheckedChange |
In shape |
| Temporarily disallow changes | disabled or loading |
Loading |
In the current API, value and defaultValue are also supported: bind:value binds the same state. Certain checked takes precedence over value, including checked=false. The defaultChecked property takes precedence over defaultValue; both initial properties are read upon creation. Do not update defaultChecked to change a radio button that is already shown.
The onCheckedChange handler receives a new boolean value. The onChange handler receives the value and mouse or keyboard event. The onClick handler is called after onChange when the button is clicked, but not when selected by the arrows. To store regular local state, bind:checked is sufficient.
Download, keyboard and design
The loading property shows an indicator and blocks state changes, including when disabled=false. The component does not wait for a Promise from the handler: the application itself starts saving, sets loading and decides how to restore the state in case of an error. Download example shows that both sizes are unavailable without network requests.
Tab turns focus to Switch. Space and Enter toggle the state; ArrowRight turns on, ArrowLeft turns off. Repeatedly arrowing to the right or left also triggers onChange, even if the state already matched the direction. Native focus and blur are available through bind:nativeElement; the same methods can be called via bind:this.
Switch has two visual sizes: medium and small. The general componentSize=large gives the normal size, and small gives the small one. Don't try to get a third size by making the text larger: adjust the design tokens if the product needs a different geometry. Example sizes shows both options.
The checkedChildren and unCheckedChildren properties accept text, numbers, or Svelte snippets. Sample content uses text and icons. root, content and indicator are available in Semantic DOM; styles accepts CSS strings, classNames accepts classes. The content slot draws up both state signatures.
Form and native submission
In Form, pass checked from form.values and update the field via onCheckedChange. FormItem binds label and messages, but does not expose state to child snippet. Example form checks the value, sends a boolean model and restores the original state when reset.
If the setting must be enabled, specify a validator that accepts true. The required rule itself does not reject false as an empty model value.
Native submission is different: enabled accessible Switch with name adds the string on to FormData. A disabled, disabled, or loading Switch is not included in this data. The value property here denotes the state, not an arbitrary sending string. For boolean data, use the Form model or explicitly convert the native result.
Examples
Basic switch
defaultChecked sets the initial state, onChange reports the new value.
<script lang="ts">
import { Switch } from '@woodger/antd';
let checked = $state(true);
</script>
<style>
.example {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
output { color: var(--ant-color-text-secondary); }
</style>
<div class="example">
<Switch defaultChecked aria-label={("Basic switch")} onChange={next => {
checked = next;
}} />
<output aria-label={("Switch state")}>{(checked ? "Included" : "Off")}</output>
</div>
Unavailable state
disabled prohibits switching with the mouse and keyboard. The button changes accessibility.
<script lang="ts">
import { Button, Switch } from '@woodger/antd';
let disabled = $state(true);
</script>
<style>
.example {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 20px;
}
</style>
<div class="example">
<Switch {disabled} defaultChecked aria-label={("Inaccessible switch")} />
<Button type="primary" onclick={() => { disabled = !disabled; }}>
{(disabled ? "Allow switching" : "Prohibit switching")}
</Button>
</div>
Text and icons
checkedChildren and unCheckedChildren accept text, numbers and Svelte snippets.
<script lang="ts">
import { Switch } from '@woodger/antd';
</script>
<style>
.example {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 20px;
}
.caption {
display: inline-flex;
align-items: center;
gap: 4px;
}
</style>
{#snippet checkIcon()}
<svg width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor"
stroke-width="2" aria-hidden="true" focusable="false"><path d="m3 8 3 3 7-7" /></svg>
{/snippet}
{#snippet closeIcon()}
<svg width="1em" height="1em" viewBox="0 0 16 16" fill="none" stroke="currentColor"
stroke-width="2" aria-hidden="true" focusable="false"><path d="m4 4 8 8m0-8-8 8" /></svg>
{/snippet}
<div class="example">
<Switch defaultChecked checkedChildren={("On")} unCheckedChildren={("Off")} aria-label={("Text states")} />
<Switch defaultChecked checkedChildren={1} unCheckedChildren={0} aria-label={("Numerical states")} />
<Switch defaultChecked checkedChildren={checkIcon} unCheckedChildren={closeIcon}
aria-label={("States with icons")} />
<Switch defaultChecked aria-label={("Text and icon")}>
{#snippet checkedChildren()}<span
class="caption"
>{@render checkIcon()}{("Yes")}</span>{/snippet}
{#snippet unCheckedChildren()}<span
class="caption"
>{@render closeIcon()}{("No")}</span>{/snippet}
</Switch>
</div>
Two sizes
Regular size medium and small small. Without local size, ConfigProvider works.
<script lang="ts">
import { Switch } from '@woodger/antd';
</script>
<style>
.example {
display: grid;
justify-items: start;
gap: 20px;
}
.row {
display: flex;
align-items: center;
gap: 12px;
}
</style>
<div class="example">
<div
class="row"
><Switch
size="medium"
defaultChecked
aria-label={("Regular size")}
/><span>{("Regular")}</span></div>
<div
class="row"
><Switch
size="small"
defaultChecked
aria-label={("Small size")}
/><span>{("Small")}</span></div>
</div>
Loading
loading shows the indicator and temporarily prohibits changing the state.
<script lang="ts">
import { Switch } from '@woodger/antd';
</script>
<style>
.example {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 20px;
}
</style>
<div class="example">
<Switch size="medium" loading defaultChecked aria-label={("Loading a normal switch")} />
<Switch size="small" loading aria-label={("Loading small switch")} />
</div>
Semantic styles
classNames and styles style the root, content and indicator elements. styles supports the function.
<script lang="ts">
import { Switch, type SwitchProps } from '@woodger/antd';
const styles: SwitchProps['styles'] = ({ props }) => ({
root: props.checked
? 'background: #389e0d'
: 'background: #595959',
content: 'font-weight: 600'
});
</script>
<style>
.example {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 24px;
}
.example :global(.switch-outline) {
outline: 2px solid var(--ant-color-border);
outline-offset: 4px;
}
</style>
<div class="example">
<Switch
defaultChecked
size="small"
checkedChildren={("On")}
unCheckedChildren={("Off")}
aria-label={("Styles by object")}
styles={{ root: 'background: #722ed1' }}
/>
<Switch defaultChecked checkedChildren={("On")} unCheckedChildren={("Off")}
aria-label={("Styles function")} classNames={{ root: 'switch-outline' }} {styles} />
</div>
State binding
In Svelte, state can be bound via bind:checked or a compatible alias bind:value.
<script lang="ts">
import { Button, Switch } from '@woodger/antd';
let checked = $state(false);
let value = $state(true);
</script>
<style>
.example {
display: grid;
justify-items: start;
gap: 20px;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
output {
color: var(--ant-color-text-secondary);
font-family: var(--ant-font-family-code);
}
</style>
<div class="example">
<div class="row">
<Switch bind:checked aria-label={("Binding checked")} />
<output
aria-label={("Value checked")}
>checked: {(String(checked))}</output>
</div>
<div class="row">
<Switch bind:value aria-label={("Binding value")} />
<output
aria-label={("Value value")}
>value: {(String(value))}</output>
</div>
<Button onclick={() => {
checked = false;
value = true;
}}>{("Return initial values")}</Button>
</div>
<script lang="ts">
import { Button, Form, FormItem, Switch, createForm } from '@woodger/antd';
const form = createForm<{ digest: boolean }>({
initialValues: { digest: false },
rules: ({
digest: [{ validator: value => value
? undefined
: "Enable the report before saving." }]
})
});
let result = $state('');
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
}
</style>
<Form {form} onFinish={values => {
result = ("digest: " + String((String(values.digest))) + "");
}}>
<FormItem name="digest" label={("Receive a weekly report")} required>
<Switch checked={form.values.digest} onCheckedChange={value => {
form.setFieldValue('digest', value);
result = '';
}} />
</FormItem>
<div class="actions">
<Button type="primary" htmlType="submit">{("Save")}</Button>
<Button htmlType="reset" onclick={() => { result = ''; }}>{("Reset")}</Button>
</div>
<output aria-label={("Form result")}>{result}</output>
</Form>
The setting is saved when switching. If there is an error, the last saved state is returned.
Notifications are turned off.
Save a setting
Toggle notifications and see how the previous setting is restored if saving fails.
SwitchExample.svelte<script lang="ts"> import { onDestroy } from 'svelte'; import { Button, Checkbox, Form, FormItem, Switch, createForm } from '@woodger/antd'; import { createSwitchSetting } from './switch-setting.model.svelte'; const generatedId = $props.id(); let failSave = $state(false); let formResult = $state(''); const setting = createSwitchSetting((_checked, signal) => { const shouldFail = failSave; failSave = false; return new Promise<void>((resolve, reject) => { const timer = setTimeout(() => { signal.removeEventListener('abort', abort); if (shouldFail) { reject(new Error(('Save failed'))); } else { resolve(); } }, 500); function abort() { clearTimeout(timer); reject(new DOMException('Save aborted', 'AbortError')); } signal.addEventListener('abort', abort, { once: true }); }); }); const form = createForm<{ digest: boolean }>({ initialValues: { digest: false }, rules: ({ digest: [ { validator: (value) => value === true ? undefined : "Enable form verification report." } ] }) }); onDestroy(setting.dispose); </script> <style> .example { max-width: 640px; } .setting { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; } .description { margin: 12px 0 16px; color: var(--ant-color-text-secondary); } .save-state { margin: 12px 0 24px; color: var(--ant-color-text-secondary); } .error { margin: 12px 0; color: var(--ant-color-error); } .actions { display: flex; flex-wrap: wrap; gap: 12px; } .result { margin: 16px 0 0; color: var(--ant-color-success); } </style> <div class="example"> <div class="setting"> <Switch id={`switch-setting-${generatedId}`} checked={setting.checked} loading={setting.loading} onCheckedChange={(value) => { void setting.change(value); }} > {#snippet checkedChildren()}{("On")}{/snippet} {#snippet unCheckedChildren()}{("Off")}{/snippet} </Switch> <label for={`switch-setting-${generatedId}`} >{("Automatic notifications")}</label> </div> <p class="description"> {("The setting is saved when switching. If there is an error, the last saved state is returned.")} </p> <Checkbox bind:checked={failSave}>{("Next save error")}</Checkbox> {#if setting.error}<p class="error" role="alert">{(setting.error)}</p>{/if} <p class="save-state" role="status" aria-label={("Saving notifications")}> {(setting.loading ? "Save the setting..." : setting.saved ? "Notifications are enabled." : "Notifications are turned off.")} </p> <Form {form} onFinish={() => { formResult = ("Parameters saved."); }}> <FormItem name="digest" label={("Weekly report")} required help={("To check the form, enable the report.")} > <Switch checked={form.values.digest} onCheckedChange={(value) => { form.setFieldValue('digest', value); formResult = ''; }} > {#snippet checkedChildren()}{("Yes")}{/snippet} {#snippet unCheckedChildren()}{("No")}{/snippet} </Switch> </FormItem> <div class="actions" ><Button type="primary" htmlType="submit" loading={form.isSubmitting} >{("Save parameters")}</Button><Button htmlType="reset" onclick={() => { formResult = ''; }} >{("Reset parameters")}</Button></div> </Form> {#if formResult} <p class="result" role="status" aria-label={("Switch form result")}> {formResult} </p> {/if} </div>switch-setting.model.svelte.tsexport type SwitchSettingSaver = (checked: boolean, signal: AbortSignal) => Promise<void>; export function createSwitchSetting(save: SwitchSettingSaver, initial = false) { let checked = $state(initial); let saved = $state(initial); let loading = $state(false); let error = $state<string | null>(null); let controller: AbortController | undefined; let disposed = false; return { get checked() { return checked; }, get saved() { return saved; }, get loading() { return loading; }, get error() { return error; }, async change(next: boolean) { if (disposed || loading || next === checked) { return; } const activeController = new AbortController(); controller = activeController; checked = next; loading = true; error = null; try { await save(next, activeController.signal); if (!disposed) saved = next; } catch { if (!disposed) { checked = saved; error = "Failed to save the setting. Try again."; } } finally { if (!disposed) { loading = false; controller = undefined; } } }, dispose() { disposed = true; controller?.abort(); controller = undefined; checked = saved; loading = false; } }; }
The prefix changes the root, handle, captions and loading. The bind:checked state, the keyboard and the native form field are preserved.
CSS prefixes Switch
Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.
<script lang="ts">
import { Checkbox, ConfigProvider, Switch } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-switch' : '');
let checked = $state(true);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("General prefix Switch suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Local prefix Switch")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'switch-theme' } }}>
<div class="prefix-stage">
<Switch
prefixCls={localPrefix}
bind:checked
checkedChildren={("On")}
unCheckedChildren={("Off")}
aria-label={("Switch with prefix")}
/>
<output aria-label={("Switch status with prefix")}>{(checked ? "Included" : "Off")}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS prefix Switch")}
>{("General: ")}{prefix}{("; local: ")}{(localPrefix
|| ("from the provider"))}</output>
<p>
{("The prefix changes the root, handle, captions and loading. The bind:checked state, the keyboard and the native form field are preserved.")}
</p>
</div>
API
Basic parameters of Switch. Precise signatures are available in public types SwitchProps and SwitchConfig installed package @woodger/antd.
| Property | Description | Type | Default |
|---|---|---|---|
prefixCls | Full CSS prefix of the component and its parts. A non-empty local prop takes precedence; empty string and undefined inherit ConfigProvider. The namespace of the topic is set separately. | SwitchProps['prefixCls'] | ant-switch |
checked | Current status; supports bind:checked and takes precedence over value. | SwitchProps['checked'] | false |
defaultChecked | Initial state without binding, false by default. Subsequent changes to the parameter do not change the state. | SwitchProps['defaultChecked'] | false |
value | Compatible alias checked; supports bind:value. | SwitchProps['value'] | — |
defaultValue | Alias initial state; defaultChecked takes precedence. | SwitchProps['defaultValue'] | — |
disabled | Disables interaction. Without a local value, inherits from Form or ConfigProvider. | SwitchProps['disabled'] | false |
loading | Shows an indicator and blocks switching, even with disabled=false. | SwitchProps['loading'] | false |
size | small or regular medium. Without size, ConfigProvider.componentSize is inherited. | SwitchProps['size'] | medium |
checkedChildren | Text, number or Svelte snippet for the enabled state. | SwitchProps['checkedChildren'] | — |
unCheckedChildren | Text, number or Svelte snippet for off state. | SwitchProps['unCheckedChildren'] | — |
onCheckedChange | Gets a new boolean value; Suitable for form model or controlled setup. | SwitchProps['onCheckedChange'] | — |
onChange | Gets the value and event after a click or arrow. The arrows also cause a callback when the state is selected again. | SwitchProps['onChange'] | — |
onClick | Receives the new value and event after onChange. Arrows do not call this callback. | SwitchProps['onClick'] | — |
classNames | CSS classes of root, content and indicator elements; object or function from { props }. | SwitchProps['classNames'] | — |
styles | CSS lines for the same elements; object or function from { props }. | SwitchProps['styles'] | — |
nativeElement | bind:nativeElement gets the native button for focus() and blur(); the link is cleared when unmounted. | SwitchProps['nativeElement'] | — |
Native attributes id, name, form and aria-* are passed to the element. Available for Svelte events onclick, onkeydown, onfocus and onblur.
ConfigProvider.switch
classstyleclassNamesstylesThe general design is specified via ConfigProvider.switch. Local semantic styles take precedence over general ones.
Semantic DOM
Select an item to see its border on the actual switch. These names are used in classNames and styles.
content applies to both status labels. Example of semantic styles shows the object and function from { props }.
Registration tokens
Component settings are transmitted via ConfigProvider.theme.components.Switch. Names are verified against public ComponentTokenMap['Switch'].
<script lang="ts">
import { ConfigProvider, Switch } from '@woodger/antd';
</script>
<ConfigProvider theme={{
cssVar: {},
components: {
Switch: {
trackHeight: 28,
trackMinWidth: 60,
handleSize: 24,
handleBg: '#f6ffed'
}
}
}}>
<Switch defaultChecked size="medium" aria-label={("Custom Switch theme")} />
</ConfigProvider>
| Token | Purpose |
|---|---|
trackHeight | Height of a conventional switch. |
trackHeightSM | Small switch height. |
trackMinWidth | Minimum width of a regular switch. |
trackMinWidthSM | Minimum width of small switch. |
trackPadding | Indentation of the indicator from the edge of the track. |
handleBg | Indicator background. |
handleShadow | Indicator shadow. |
handleSize | The size of a regular indicator. |
handleSizeSM | Small indicator size. |
innerMinMargin | Less internal padding of a conventional switch label. |
innerMaxMargin | Larger internal indentation of the label of a conventional switch. |
innerMinMarginSM | Smaller internal padding of the small switch label. |
innerMaxMarginSM | Larger internal padding of the small switch label. |
Common tokens of the current topic
Values obtained via theme.useToken() and respond to settings in the Ant Design header.
| Token | Purpose | Current value |
|---|---|---|
colorPrimary | Background of the switch on. | #2f54eb |
colorPrimaryHover | Background of the enabled switch when hovering. | #597ef7 |
colorTextQuaternary | Background of a switch that is turned off. | rgba(0,0,0,0.25) |
colorTextTertiary | Background of the switch that is turned off when hovering. | rgba(0,0,0,0.45) |
motionDurationMid | Transition duration. | 0.2s |
FAQ
How to connect Switch to Form?
Pass checked from form.values and update the field via onCheckedChange. The model stores boolean. Example form also shows check, send and reset; setting valuePropName from the React examples is not needed here.
Why doesn't changing defaultChecked change the switch?
Properties defaultChecked and defaultValue specify the initial state. For subsequent changes, use bind:checked, bind:value, or managed checked. If checked and value are passed at the same time, the specified checked takes precedence even when it is false.
Why doesn't FormData contain false?
The native data contains the line on only for the enabled accessible Switch with name. A disabled or disabled switch is not sent. boolean false is stored in the Form model, not in the native FormData.
How to control from the keyboard and change focus?
Tab transfers focus, Space and Enter switch state. ArrowRight turns on, ArrowLeft turns off. Use bind:nativeElement or focus/blur methods via bind:this. The name of the setting should remain clear to assistive technologies.
Why is there no separate large size?
Switch has two visual dimensions. large from the general setting corresponds to a regular Switch, small to small. Example sizes and tokens show the available design methods.
loading itself saves the value?
No, it shows wait and blocks the switch. The request, error handling, and rollback belong to the application; the component does not manage the Promise handler.