Leave Yamada UI a star

Star
Yamada UIYamada UIv1.5.0

Switch

Switch is a component used to toggle between on and off states.

Source@yamada-ui/switch

Import

import { Switch } from "@yamada-ui/react"
Copied!

Usage

Editable example

<Switch>basic</Switch>
Copied!

Change Variant

Editable example

<Wrap gap="md">
  <Switch variant="thick">thick</Switch>
  <Switch variant="thin">thin</Switch>
</Wrap>
Copied!

Change Size

Editable example

<Wrap gap="md">
  <Switch size="sm">small size</Switch>
  <Switch size="md">medium size</Switch>
  <Switch size="lg">large size</Switch>
</Wrap>
Copied!

Change Color Scheme

Editable example

<Wrap gap="md">
  <Switch colorScheme="secondary" defaultIsChecked>
    Secondary
  </Switch>
  <Switch colorScheme="green" defaultIsChecked>
    Green
  </Switch>
</Wrap>
Copied!

Change Label Position

To change the label position, set isReverse to true.

Editable example

<Switch isReverse>basic</Switch>
Copied!

Disable

To disable, set isDisabled to true.

Editable example

<Wrap gap="md">
  <Switch isDisabled>disabled</Switch>
  <Switch isDisabled defaultIsChecked>
    disabled
  </Switch>
</Wrap>
Copied!

Make Read-Only

To make read-only, set isReadOnly to true.

Editable example

<Wrap gap="md">
  <Switch isReadOnly>read only</Switch>
  <Switch isReadOnly defaultIsChecked>
    read only
  </Switch>
</Wrap>
Copied!

Customize Label

To customize the label, use Label.

Editable example

const id = useId()

return (
  <HStack gap="sm">
    <Label htmlFor={id} userSelect="none">
      Please Click
    </Label>
    <Switch id={id} />
  </HStack>
)
Copied!

Control

Editable example

const [isChecked, { toggle }] = useBoolean(false)

return (
  <Switch isChecked={isChecked} onChange={toggle}>
    custom control
  </Switch>
)
Copied!

Use React Hook Form

Editable example

type Data = { switch: boolean }

const { control, handleSubmit, watch } = useForm<Data>()

const onSubmit: SubmitHandler<Data> = (data) => console.log("submit:", data)

console.log("watch:", watch())

return (
  <VStack as="form" onSubmit={handleSubmit(onSubmit)}>
    <Controller
      name="switch"
      control={control}
      render={({ field: { value, ...rest } }) => (
        <Switch isChecked={value} {...rest}>
          Dark mode
        </Switch>
      )}
    />

    <Button type="submit" alignSelf="flex-end">
      Submit
    </Button>
  </VStack>
)
Copied!

Edit this page on GitHub

PreviousSliderNextTextarea