DXC Logo

Switch

A switch allows users to toggle a single setting between two opposing states, such as on/off or enabled/disabled. It represents a binary choice that takes effect immediately.

Props

NameTypeDescriptionDefault
ariaLabelstringSpecifies a string to be used as the name for the switch element when no label is provided.'Switch'
checkedbooleanIf true, the component is checked. If undefined, the component will be uncontrolled and the checked attribute will be managed internally by the component.-
defaultCheckedbooleanInitial state of the switch, only when it is uncontrolled.false
disabledbooleanIf true, the component will be disabled.false
labelstringText to be placed next to the switch.-
labelPosition'before' | 'after'Whether the label should appear after or before the switch.'before'
margin'xxsmall' | 'xsmall' | 'small' | 'medium' | 'large' | 'xlarge' | 'xxlarge' | MarginSize of the margin to be applied to the component. You can pass an object with 'top', 'bottom', 'left' and 'right' properties in order to specify different margin sizes.-
namestringName attribute of the input element.-
onChange(checked: boolean) => voidThis function will be called when the user clicks the switch. The new value of the checked attribute will be passed as a parameter.-
optionalbooleanIf true, the component will display '(Optional)' next to the label.false
refReact.Ref<HTMLDivElement>Reference to the component.-
size'small' | 'medium' | 'large' | 'fillParent' | 'fitContent'Size of the component.'fitContent'
tabIndexnumberValue of the tabindex attribute.0
valuestringWill be passed to the value attribute of the HTML input element. When inside a form, this value will be only submitted if the switch is checked.-

Examples

Controlled

() => {
  const [checked, changeChecked] = useState(false);
  const onChange = (newValue) => {
    changeChecked(newValue);
  };

  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcSwitch
        label="Wifi"
        checked={checked}
        onChange={onChange}
      />
    </DxcInset>
  );
}

Uncontrolled

() => {
  const switchRef = useRef();

  const handleSubmit = () => {
    const switchEl = switchRef.current.getElementsByTagName("input")[0];
    console.log(switchEl.checked ? switchEl.value : "");
  };

  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcFlex direction="column" gap="var(--spacing-gap-xl)">
        <DxcSwitch
          label="Bluetooth"
          defaultChecked
          ref={switchRef}
          value="Bluetooth"
        />
        <DxcButton label="Submit" type="submit" onClick={handleSubmit} />
      </DxcFlex>
    </DxcInset>
  );
}