Components
Checkbox

Checkbox

The Checkbox is a widely used input component for toggling between checked and unchecked states. It supports basic, controlled, and indeterminate states.

Usage

To get started, import the necessary components from the package:

import { Checkbox, CheckboxLabel, CheckboxControl } from '@ark-ui/react'

Here is an example of how to use the Checkbox component:

import { useState } from 'react'
import { Checkbox, CheckboxControl, CheckboxLabel, type CheckedState } from '@ark-ui/react'

const Basic = () => (
  <Checkbox defaultChecked>
    <CheckboxLabel>Checkbox</CheckboxLabel>
    <CheckboxControl />
  </Checkbox>
)

Controlled Checkbox

To create a controlled Checkbox component, manage the state of the checked status using the checked prop and update it when the onChange event handler is called:

import { useState } from 'react'
import { Checkbox, CheckboxControl, CheckboxLabel, type CheckedState } from '@ark-ui/react'

const Controlled = () => {
  const [checked, setChecked] = useState<CheckedState>(true)
  return (
    <>
      <Checkbox checked={checked} onCheckedChange={(e) => setChecked(e.checked)}>
        <CheckboxLabel>Checkbox</CheckboxLabel>
        <CheckboxControl />
      </Checkbox>
    </>
  )
}

Indeterminate Checkbox

In some cases, you may need a checkbox to represent a state that is neither checked nor unchecked, known as the indeterminate state. This can be achieved by setting the checked prop to indeterminate:

import { useState } from 'react'
import { Checkbox, CheckboxControl, CheckboxLabel, type CheckedState } from '@ark-ui/react'

const Indeterminate = () => (
  <Checkbox checked="indeterminate">
    <CheckboxLabel>Checkbox</CheckboxLabel>
    <CheckboxControl />
  </Checkbox>
)

Render Prop Usage

For cases where you need more flexibility in rendering, the Checkbox component offers the use of a render prop. The render prop function gives you access to the checkbox’s API, allowing you to customize the checkbox control’s rendering:

import { useState } from 'react'
import { Checkbox, CheckboxControl, CheckboxLabel, type CheckedState } from '@ark-ui/react'

const RenderProp = () => (
  <Checkbox>
    {(api) => (
      <>
        <CheckboxLabel>Checkbox</CheckboxLabel>
        <CheckboxControl>
          {api.isChecked && <span>✓</span>}
          {api.isIndeterminate && <span>-</span>}
        </CheckboxControl>
      </>
    )}
  </Checkbox>
)

Conclusion

The Checkbox component provides a robust and flexible solution for toggleable input needs in your applications. With its support for controlled and indeterminate states, as well as custom render props, it offers a wide range of design possibilities and use cases.

Previous

Carousel