Switch

Switching Selector.

When To Use#

  • If you need to represent the switching between two states or on-off state.

  • The difference between Switch and Checkbox is that Switch will trigger a state change directly when you toggle it, while Checkbox is generally used for state marking, which should work in conjunction with submit operation.

Examples

The most basic usage.

expand codeexpand code
import { Switch } from 'antd';

function onChange(checked) {
  console.log(`switch to ${checked}`);
}

ReactDOM.render(<Switch defaultChecked onChange={onChange} />, mountNode);


With text and icon.

expand codeexpand code
import { Switch, Icon } from 'antd';

ReactDOM.render(
  <div>
    <Switch checkedChildren="" unCheckedChildren="" defaultChecked />
    <br />
    <Switch checkedChildren="1" unCheckedChildren="0" />
    <br />
    <Switch
      checkedChildren={<Icon type="check" />}
      unCheckedChildren={<Icon type="close" />}
      defaultChecked
    />
  </div>,
  mountNode,
);

Mark a pending state of switch.

expand codeexpand code
import { Switch } from 'antd';

ReactDOM.render(
  <div>
    <Switch loading defaultChecked />
    <br />
    <Switch size="small" loading />
  </div>,
  mountNode,
);

Disabled state of Switch.

expand codeexpand code
import { Switch, Button } from 'antd';

class App extends React.Component {
  state = {
    disabled: true,
  };

  toggle = () => {
    this.setState({
      disabled: !this.state.disabled,
    });
  };

  render() {
    return (
      <div>
        <Switch disabled={this.state.disabled} defaultChecked />
        <br />
        <Button type="primary" onClick={this.toggle}>
          Toggle disabled
        </Button>
      </div>
    );
  }
}

ReactDOM.render(<App />, mountNode);

size="small" represents a small sized switch.

expand codeexpand code
import { Switch } from 'antd';

ReactDOM.render(
  <div>
    <Switch defaultChecked />
    <br />
    <Switch size="small" defaultChecked />
  </div>,
  mountNode,
);

API#

PropertyDescriptionTypeDefaultVersion
autoFocusget focus when component mountedbooleanfalse
checkeddetermine whether the Switch is checkedbooleanfalse
checkedChildrencontent to be shown when the state is checkedstring|ReactNode
defaultCheckedto set the initial statebooleanfalse
disabledDisable switchbooleanfalse
loadingloading state of switchbooleanfalse
sizethe size of the Switch, options: default smallstringdefault
unCheckedChildrencontent to be shown when the state is uncheckedstring|ReactNode
onChangetrigger when the checked state is changingFunction(checked: boolean, event: Event)
onClicktrigger when clickedFunction(checked: boolean, event: Event)3.13.0
classNameadditional class to Switchstring-3.10.1

Methods#

NameDescriptionVersion
blur()remove focus
focus()get focus
RadioSlider