JGuang

Switch

Switch · Ant Design Mobile

Preview
npm install antd-mobile@5.43.0

Switch

switch selector.

Install

npm install antd-mobile@5.43.0

antd-mobile is for mobile web, not React Native or Mini Programs. React 19 projects must register createRoot with unstableSetRender at the entry, or imperative APIs such as Toast and Dialog cannot render. Switch dark mode with <html data-prefers-color-scheme="dark">.

Examples come from the official Ant Design Mobile repository (MIT) at the commit published as npm 5.43.0. Presentation helpers such as DemoBlock are JGuang rewrites, not antd-mobile APIs.

switch selector.

When to Use

  • When it is necessary to represent a switch state/switch between two states.
  • The difference from checkbox is that switching switch will directly trigger state change, while checkbox is generally used for state marking and needs to cooperate with submit operation.

Demos

Switch

Props

NameDescriptionTypeDefault
beforeChange(deprecated)Execute before change (Deprecated, recommend using the onChange attribute.)(val: boolean) => Promise<void>-
checkedSpecify whether it is currently openedbooleanfalse
checkedTextSelected textReactNode-
defaultCheckedWhether to open initiallybooleanfalse
disabledDisabled statusbooleanfalse
loadingLoading statusbooleanfalse
onChangeThe callback function when changing, when the Promise is returned, the loading status will be displayed automatically(val: boolean) => void | Promise<void>-
uncheckedTextNon-selected textReactNode-

CSS Variables

NameDescriptionDefault
--border-widthBorder width2px
--checked-colorFilled colorvar(--adm-color-primary)
--heightHeight31px
--widthWidth51px

FAQ

How to handle exceptions in async onChange?

The onChange event supports returning a Promise, when the Promise starts, the Switch will automatically enter the loading state, and when the Promise completes or fails, the Switch will automatically exit the loading state. In general, this satisfies the needs of most projects.

But when Promise fails, Switch will not eat the error, but will re-throw the error object. This is the expected behavior. If you want to intercept some errors yourself and avoid them being thrown, you can use try/ catch wraps the processing logic in onChange, for example:

async function onChange(val: boolean) {
  try {
    await doSomething();
  } catch (e) {
    // handle or ignore error
  }
}