Ant Design Svelte

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

Included

Basic switch

defaultChecked sets the initial state, onChange reports the new value.

Unavailable state

disabled prohibits switching with the mouse and keyboard. The button changes accessibility.

Text and icons

checkedChildren and unCheckedChildren accept text, numbers and Svelte snippets.

Regular
Small

Two sizes

Regular size medium and small small. Without local size, ConfigProvider works.

Loading

loading shows the indicator and temporarily prohibits changing the state.

Semantic styles

classNames and styles style the root, content and indicator elements. styles supports the function.

checked: false
value: true

State binding

In Svelte, state can be bound via bind:checked or a compatible alias bind:value.

In shape

The Form model stores boolean. The example shows checking, sending and resetting a value.

The setting is saved when switching. If there is an error, the last saved state is returned.

Notifications are turned off.

To check the form, enable the report.

Save a setting

Toggle notifications and see how the previous setting is restored if saving fails.

Included
General: suite; local: project-switch

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.

API

Basic parameters of Switch. Precise signatures are available in public types SwitchProps and SwitchConfig installed package @woodger/antd.

Basic parameters of Switch
PropertyDescriptionTypeDefault
prefixClsFull 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
checkedCurrent status; supports bind:checked and takes precedence over value.SwitchProps['checked']false
defaultCheckedInitial state without binding, false by default. Subsequent changes to the parameter do not change the state.SwitchProps['defaultChecked']false
valueCompatible alias checked; supports bind:value.SwitchProps['value']—
defaultValueAlias ​​initial state; defaultChecked takes precedence.SwitchProps['defaultValue']—
disabledDisables interaction. Without a local value, inherits from Form or ConfigProvider.SwitchProps['disabled']false
loadingShows an indicator and blocks switching, even with disabled=false.SwitchProps['loading']false
sizesmall or regular medium. Without size, ConfigProvider.componentSize is inherited.SwitchProps['size']medium
checkedChildrenText, number or Svelte snippet for the enabled state.SwitchProps['checkedChildren']—
unCheckedChildrenText, number or Svelte snippet for off state.SwitchProps['unCheckedChildren']—
onCheckedChangeGets a new boolean value; Suitable for form model or controlled setup.SwitchProps['onCheckedChange']—
onChangeGets the value and event after a click or arrow. The arrows also cause a callback when the state is selected again.SwitchProps['onChange']—
onClickReceives the new value and event after onChange. Arrows do not call this callback.SwitchProps['onClick']—
classNamesCSS classes of root, content and indicator elements; object or function from { props }.SwitchProps['classNames']—
stylesCSS lines for the same elements; object or function from { props }.SwitchProps['styles']—
nativeElementbind: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

classstyleclassNamesstyles

The 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.

root: Native button with the switch role: track and states.

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>
Switch component tokens
TokenPurpose
trackHeightHeight of a conventional switch.
trackHeightSMSmall switch height.
trackMinWidthMinimum width of a regular switch.
trackMinWidthSMMinimum width of small switch.
trackPaddingIndentation of the indicator from the edge of the track.
handleBgIndicator background.
handleShadowIndicator shadow.
handleSizeThe size of a regular indicator.
handleSizeSMSmall indicator size.
innerMinMarginLess internal padding of a conventional switch label.
innerMaxMarginLarger internal indentation of the label of a conventional switch.
innerMinMarginSMSmaller internal padding of the small switch label.
innerMaxMarginSMLarger 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.

Common tokens of the current topic
TokenPurposeCurrent value
colorPrimaryBackground of the switch on.#2f54eb
colorPrimaryHoverBackground of the enabled switch when hovering.#597ef7
colorTextQuaternaryBackground of a switch that is turned off.rgba(0,0,0,0.25)
colorTextTertiaryBackground of the switch that is turned off when hovering.rgba(0,0,0,0.45)
motionDurationMidTransition 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.