Switch

A control element that allows for a binary selection.

Anatomy

To set up the switch correctly, you’ll need to understand its anatomy and how we name its parts.

Each part includes a data-part attribute to help identify them in the DOM.

Examples

Learn how to use the Switch component in your project. Let’s take a look at the most basic example:

import { Switch } from '@ark-ui/react'

const Basic = () => (
  <Switch.Root>
    <Switch.Control>
      <Switch.Thumb />
    </Switch.Control>
    <Switch.Label>Label</Switch.Label>
  </Switch.Root>
)

Controlled Switch

For a controlled Switch component, the state of the toggle is managed using the checked prop, and updates when the onCheckedChange event handler is called:

import { Switch } from '@ark-ui/react'
import { useState } from 'react'

const Controlled = () => {
  const [checked, setChecked] = useState(false)

  return (
    <Switch.Root checked={checked} onCheckedChange={(e) => setChecked(e.checked)}>
      <Switch.Control>
        <Switch.Thumb />
      </Switch.Control>
      <Switch.Label>Label</Switch.Label>
    </Switch.Root>
  )
}

Render Prop Usage

The Switch component also allows for a render prop, granting direct access to its internal state. This enables you to dynamically adjust and customize aspects of the component based on its current state:

import { Switch } from '@ark-ui/react'

const RenderProp = () => (
  <Switch.Root>
    {(api) => (
      <>
        <Switch.Control>
          <Switch.Thumb />
        </Switch.Control>
        <Switch.Label>Feature is {api.isChecked ? 'enabled' : 'disabled'}</Switch.Label>
      </>
    )}
  </Switch.Root>
)

API Reference

Root

PropTypeDefault
asChild
boolean
checked
boolean
defaultChecked
boolean
dir
'ltr' | 'rtl'"ltr"
disabled
boolean
form
string
getRootNode
() => Node | ShadowRoot | Document
id
string
ids
Partial<{ root: string input: string control: string label: string thumb: string }>
invalid
boolean
label
string
name
string
onCheckedChange
(details: CheckedChangeDetails) => void
required
boolean
value
string | number"on"

Label

PropTypeDefault
asChild
boolean

Thumb

PropTypeDefault
asChild
boolean

Control

PropTypeDefault
asChild
boolean

Previous

Splitter

Next

Tabs