Components
Switch

Switch

The Switch is an interactive, binary component designed for your applications. It offers a clear, visual interface for users to enable or disable specific settings, features, or functionalities.

Usage

To use the Switch component in your project, import the necessary sub-components from the package:

import { Switch, SwitchControl, SwitchThumb, SwitchLabel } from '@ark-ui/react'

Here is a basic example of how to use the Switch component:

import { useState } from 'react'
import { Switch, SwitchControl, SwitchLabel, SwitchThumb } from '@ark-ui/react'

const Basic = () => (
  <Switch defaultChecked>
    <SwitchControl>
      <SwitchThumb />
    </SwitchControl>
    <SwitchLabel>Label</SwitchLabel>
  </Switch>
)

Controlled Switch

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

import { useState } from 'react'
import { Switch, SwitchControl, SwitchLabel, SwitchThumb } from '@ark-ui/react'

const Controlled = () => {
  const [checked, setChecked] = useState(false)
  return (
    <Switch checked={checked} onCheckedChange={(e) => setChecked(e.checked)}>
      <SwitchControl>
        <SwitchThumb />
      </SwitchControl>
      <SwitchLabel>Label</SwitchLabel>
    </Switch>
  )
}

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 { useState } from 'react'
import { Switch, SwitchControl, SwitchLabel, SwitchThumb } from '@ark-ui/react'

const RenderProp = () => (
  <Switch>
    {(api) => (
      <>
        <SwitchControl>
          <SwitchThumb />
        </SwitchControl>
        <SwitchLabel>Feature is {api.isChecked ? 'enabled' : 'disabled'}</SwitchLabel>
      </>
    )}
  </Switch>
)

Conclusion

The Switch component provides a straightforward, intuitive solution for incorporating toggle functionality into your applications. With its flexibility for both controlled and uncontrolled scenarios and provision for dynamic customization through its render prop, it can accommodate various use cases effectively.

Previous

Splitter

Next

Tabs