Switch

Capture boolean input from users with a toggle switch control.

Import

import { Switch } from '@tidbcloud/uikit'

Basic Usage

import { Switch } from '@tidbcloud/uikit'
 
function Demo() {
  return <Switch defaultChecked label="I agree to sell my privacy" />
}

Controlled

import { useState } from 'react'
import { Switch } from '@tidbcloud/uikit'
 
function Demo() {
  const [checked, setChecked] = useState(false)
  return <Switch checked={checked} onChange={(event) => setChecked(event.currentTarget.checked)} />
}

With Inner Labels

import { Switch, Group } from '@tidbcloud/uikit'
 
function Demo() {
  return (
    <Group>
      <Switch size="xs" onLabel="ON" offLabel="OFF" />
      <Switch size="sm" onLabel="ON" offLabel="OFF" />
      <Switch size="md" onLabel="ON" offLabel="OFF" />
      <Switch size="lg" onLabel="ON" offLabel="OFF" />
    </Group>
  )
}

With Thumb Icon

import { useState } from 'react'
import { Switch } from '@tidbcloud/uikit'
import { IconCheck, IconX } from '@tabler/icons-react'
 
function Demo() {
  const [checked, setChecked] = useState(false)
 
  return (
    <Switch
      checked={checked}
      onChange={(event) => setChecked(event.currentTarget.checked)}
      color="teal"
      size="md"
      label="Switch with thumb icon"
      thumbIcon={
        checked ? (
          <IconCheck size={12} color="var(--mantine-color-teal-6)" stroke={3} />
        ) : (
          <IconX size={12} color="var(--mantine-color-red-6)" stroke={3} />
        )
      }
    />
  )
}

Switch.Group

import { Switch, Group } from '@tidbcloud/uikit'
 
function Demo() {
  return (
    <Switch.Group defaultValue={['react']} label="Select frameworks">
      <Group mt="xs">
        <Switch value="react" label="React" />
        <Switch value="svelte" label="Svelte" />
        <Switch value="ng" label="Angular" />
        <Switch value="vue" label="Vue" />
      </Group>
    </Switch.Group>
  )
}

Key Props

PropTypeDescription
checkedbooleanControlled checked state
defaultCheckedbooleanDefault checked state
onChange(event) => voidCalled when value changes
labelReactNodeLabel associated with the switch
descriptionReactNodeDescription below the label
errorReactNodeError message below the label
sizeMantineSizeControls size of elements
colorMantineColorColor when checked
onLabelReactNodeInner label when checked
offLabelReactNodeInner label when unchecked
thumbIconReactNodeIcon inside the thumb
labelPosition”left” | “right”Label position
disabledbooleanDisables the switch