Skip to content

Checkbox

An input element to toggle between checked and unchecked states.

Demo

This requires the following components to be installed:

This requires the following composables to be installed:

This requires the following types to be installed:

This requires the following theme to be installed:

Component

Checkbox.vue
vue
<script lang="ts">
import type { ComponentConfig } from '@/ui/utils/utils'
import type { CheckboxRootProps } from 'reka-ui'
import Icon from '@/ui/components/Icon.vue'
import { useFormField } from '@/ui/composables/useFormField'
import { checkIcon, minusIcon } from '@/ui/icons'
import theme from '@/ui/theme/checkbox'
import { reactivePick } from '@vueuse/shared'
import { CheckboxIndicator, CheckboxRoot, Label, Primitive, useForwardProps } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, useId } from 'vue'

type Checkbox = ComponentConfig<typeof theme>

export interface CheckboxProps extends Pick<CheckboxRootProps, 'disabled' | 'required' | 'name' | 'value' | 'id' | 'defaultValue'> {
  as?: any
  label?: string
  description?: string
  color?: Checkbox['variants']['color']
  variant?: Checkbox['variants']['variant']
  size?: Checkbox['variants']['size']
  indicator?: Checkbox['variants']['indicator']
  icon?: string
  indeterminateIcon?: string
  class?: any
  ui?: Checkbox['slots']
}

export interface CheckboxEmits {
  change: [payload: Event]
}

export interface CheckboxSlots {
  label: (props: { label?: string }) => any
  description: (props: { description?: string }) => any
}
</script>

<script setup lang="ts">
defineOptions({ inheritAttrs: false })

const props = defineProps<CheckboxProps>()
const emits = defineEmits<CheckboxEmits>()
const slots = defineSlots<CheckboxSlots>()

const modelValue = defineModel<boolean | 'indeterminate'>({ default: undefined })

const rootProps = useForwardProps(reactivePick(props, 'required', 'value', 'defaultValue'))

const { id: _id, size, color, name, disabled, ariaAttrs } = useFormField<CheckboxProps>(props)
const id = _id.value ?? useId()

const ui = computed(() => tv(theme)({
  size: size.value,
  color: color.value,
  variant: props.variant,
  indicator: props.indicator,
  required: props.required,
  disabled: disabled.value,
}))

function onUpdate(value: any) {
  // @ts-expect-error - 'target' does not exist in type 'EventInit'
  const event = new Event('change', { target: { value } })
  emits('change', event)
}
</script>

<!-- eslint-disable vue/no-template-shadow -->
<template>
  <Primitive :as="variant === 'list' ? as : Label" :class="ui.root({ class: [props.class, props.ui?.root] })">
    <div :class="ui.container({ class: props.ui?.container })">
      <CheckboxRoot
        :id="id"
        v-bind="{ ...rootProps, ...$attrs, ...ariaAttrs }"
        v-model="modelValue"
        :name="name"
        :disabled="disabled"
        :class="ui.base({ class: props.ui?.base })"
        @update:model-value="onUpdate"
      >
        <template #default="{ modelValue }">
          <CheckboxIndicator :class="ui.indicator({ class: props.ui?.indicator })">
            <Icon v-if="modelValue === 'indeterminate'" :name="props.indeterminateIcon ?? minusIcon" :class="ui.icon({ class: props.ui?.icon })" />
            <Icon v-else :name="props.icon ?? checkIcon" :class="ui.icon({ class: props.ui?.icon })" />
          </CheckboxIndicator>
        </template>
      </CheckboxRoot>
    </div>

    <div v-if="(label || !!slots.label) || (description || !!slots.description)" :class="ui.wrapper({ class: props.ui?.wrapper })">
      <component :is="variant === 'list' ? Label : 'p'" v-if="label || !!slots.label" :for="id" :class="ui.label({ class: props.ui?.label })">
        <slot name="label" :label="label">
          {{ label }}
        </slot>
      </component>
      <p v-if="description || !!slots.description" :class="ui.description({ class: props.ui?.description })">
        <slot name="description" :description="description">
          {{ description }}
        </slot>
      </p>
    </div>
  </Primitive>
</template>
Checkbox.vue
vue
<script lang="ts">
import type { ComponentConfig } from '@/UI/Utils/utils'
import type { CheckboxRootProps } from 'reka-ui'
import Icon from '@/UI/Components/Icon.vue'
import { useFormField } from '@/UI/Composables/useFormField'
import { checkIcon, minusIcon } from '@/UI/icons'
import theme from '@/UI/Theme/checkbox'
import { reactivePick } from '@vueuse/shared'
import { CheckboxIndicator, CheckboxRoot, Label, Primitive, useForwardProps } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, useId } from 'vue'

type Checkbox = ComponentConfig<typeof theme>

export interface CheckboxProps extends Pick<CheckboxRootProps, 'disabled' | 'required' | 'name' | 'value' | 'id' | 'defaultValue'> {
  as?: any
  label?: string
  description?: string
  color?: Checkbox['variants']['color']
  variant?: Checkbox['variants']['variant']
  size?: Checkbox['variants']['size']
  indicator?: Checkbox['variants']['indicator']
  icon?: string
  indeterminateIcon?: string
  class?: any
  ui?: Checkbox['slots']
}

export interface CheckboxEmits {
  change: [payload: Event]
}

export interface CheckboxSlots {
  label: (props: { label?: string }) => any
  description: (props: { description?: string }) => any
}
</script>

<script setup lang="ts">
defineOptions({ inheritAttrs: false })

const props = defineProps<CheckboxProps>()
const emits = defineEmits<CheckboxEmits>()
const slots = defineSlots<CheckboxSlots>()

const modelValue = defineModel<boolean | 'indeterminate'>({ default: undefined })

const rootProps = useForwardProps(reactivePick(props, 'required', 'value', 'defaultValue'))

const { id: _id, size, color, name, disabled, ariaAttrs } = useFormField<CheckboxProps>(props)
const id = _id.value ?? useId()

const ui = computed(() => tv(theme)({
  size: size.value,
  color: color.value,
  variant: props.variant,
  indicator: props.indicator,
  required: props.required,
  disabled: disabled.value,
}))

function onUpdate(value: any) {
  // @ts-expect-error - 'target' does not exist in type 'EventInit'
  const event = new Event('change', { target: { value } })
  emits('change', event)
}
</script>

<!-- eslint-disable vue/no-template-shadow -->
<template>
  <Primitive :as="variant === 'list' ? as : Label" :class="ui.root({ class: [props.class, props.ui?.root] })">
    <div :class="ui.container({ class: props.ui?.container })">
      <CheckboxRoot
        :id="id"
        v-bind="{ ...rootProps, ...$attrs, ...ariaAttrs }"
        v-model="modelValue"
        :name="name"
        :disabled="disabled"
        :class="ui.base({ class: props.ui?.base })"
        @update:model-value="onUpdate"
      >
        <template #default="{ modelValue }">
          <CheckboxIndicator :class="ui.indicator({ class: props.ui?.indicator })">
            <Icon v-if="modelValue === 'indeterminate'" :name="props.indeterminateIcon ?? minusIcon" :class="ui.icon({ class: props.ui?.icon })" />
            <Icon v-else :name="props.icon ?? checkIcon" :class="ui.icon({ class: props.ui?.icon })" />
          </CheckboxIndicator>
        </template>
      </CheckboxRoot>
    </div>

    <div v-if="(label || !!slots.label) || (description || !!slots.description)" :class="ui.wrapper({ class: props.ui?.wrapper })">
      <component :is="variant === 'list' ? Label : 'p'" v-if="label || !!slots.label" :for="id" :class="ui.label({ class: props.ui?.label })">
        <slot name="label" :label="label">
          {{ label }}
        </slot>
      </component>
      <p v-if="description || !!slots.description" :class="ui.description({ class: props.ui?.description })">
        <slot name="description" :description="description">
          {{ description }}
        </slot>
      </p>
    </div>
  </Primitive>
</template>

Theme

checkbox.ts
ts
export default {
  slots: {
    root: '',
    container: '',
    base: '',
    indicator: '',
    icon: '',
    wrapper: '',
    label: '',
    description: '',
  },
  variants: {
    color: {
      primary: {
        base: '',
        indicator: '',
      },
      secondary: {
        base: '',
        indicator: '',
      },
      success: {
        base: '',
        indicator: '',
      },
      info: {
        base: '',
        indicator: '',
      },
      warning: {
        base: '',
        indicator: '',
      },
      error: {
        base: '',
        indicator: '',
      },
      neutral: {
        base: '',
        indicator: '',
      },
    },
    variant: {
      list: {
        root: '',
      },
      card: {
        root: '',
      },
    },
    indicator: {
      start: {
        root: '',
        wrapper: '',
      },
      end: {
        root: '',
        wrapper: '',
      },
      hidden: {
        base: '',
        wrapper: '',
      },
    },
    size: {
      xs: {
        base: '',
        container: '',
        wrapper: '',
      },
      sm: {
        base: '',
        container: '',
        wrapper: '',
      },
      md: {
        base: '',
        container: '',
        wrapper: '',
      },
      lg: {
        base: '',
        container: '',
        wrapper: '',
      },
      xl: {
        base: '',
        container: '',
        wrapper: '',
      },
    },
    required: {
      true: {
        label: '',
      },
    },
    disabled: {
      true: {
        base: '',
        label: '',
        description: '',
      },
    },
    checked: {
      true: '',
    },
  },
  compoundVariants: [],
  defaultVariants: {
    size: 'md',
    color: 'primary',
    variant: 'list',
    indicator: 'start',
  } as const,
}
View Nuxt UI theme
checkbox.ts
ts
export default {
  slots: {
    root: 'relative flex items-start',
    container: 'flex items-center',
    base: 'rounded-sm ring ring-inset ring-accented overflow-hidden focus-visible:outline-2 focus-visible:outline-offset-2',
    indicator: 'flex items-center justify-center size-full text-inverted',
    icon: 'shrink-0 size-full',
    wrapper: 'w-full',
    label: 'block font-medium text-default',
    description: 'text-muted',
  },
  variants: {
    color: {
      primary: {
        base: 'focus-visible:outline-primary',
        indicator: 'bg-primary',
      },
      secondary: {
        base: 'focus-visible:outline-secondary',
        indicator: 'bg-secondary',
      },
      success: {
        base: 'focus-visible:outline-success',
        indicator: 'bg-success',
      },
      info: {
        base: 'focus-visible:outline-info',
        indicator: 'bg-info',
      },
      warning: {
        base: 'focus-visible:outline-warning',
        indicator: 'bg-warning',
      },
      error: {
        base: 'focus-visible:outline-error',
        indicator: 'bg-error',
      },
      neutral: {
        base: 'focus-visible:outline-inverted',
        indicator: 'bg-inverted',
      },
    },
    variant: {
      list: {
        root: '',
      },
      card: {
        root: 'border border-muted rounded-lg',
      },
    },
    indicator: {
      start: {
        root: 'flex-row',
        wrapper: 'ms-2',
      },
      end: {
        root: 'flex-row-reverse',
        wrapper: 'me-2',
      },
      hidden: {
        base: 'sr-only',
        wrapper: 'text-center',
      },
    },
    size: {
      xs: {
        base: 'size-3',
        container: 'h-4',
        wrapper: 'text-xs',
      },
      sm: {
        base: 'size-3.5',
        container: 'h-4',
        wrapper: 'text-xs',
      },
      md: {
        base: 'size-4',
        container: 'h-5',
        wrapper: 'text-sm',
      },
      lg: {
        base: 'size-4.5',
        container: 'h-5',
        wrapper: 'text-sm',
      },
      xl: {
        base: 'size-5',
        container: 'h-6',
        wrapper: 'text-base',
      },
    },
    required: {
      true: {
        label: 'after:content-[\'*\'] after:ms-0.5 after:text-error',
      },
    },
    disabled: {
      true: {
        base: 'cursor-not-allowed opacity-75',
        label: 'cursor-not-allowed opacity-75',
        description: 'cursor-not-allowed opacity-75',
      },
    },
    checked: {
      true: '',
    },
  },
  compoundVariants: [
    {
      size: 'xs',
      variant: 'card',
      class: {
        root: 'p-2.5',
      },
    } as const,
    {
      size: 'sm',
      variant: 'card',
      class: {
        root: 'p-3',
      },
    } as const,
    {
      size: 'md',
      variant: 'card',
      class: {
        root: 'p-3.5',
      },
    } as const,
    {
      size: 'lg',
      variant: 'card',
      class: {
        root: 'p-4',
      },
    } as const,
    {
      size: 'xl',
      variant: 'card',
      class: {
        root: 'p-4.5',
      },
    } as const,
    {
      color: 'primary',
      variant: 'card',
      class: {
        root: 'has-data-[state=checked]:border-primary',
      },
    } as const,
    {
      color: 'secondary',
      variant: 'card',
      class: {
        root: 'has-data-[state=checked]:border-secondary',
      },
    } as const,
    {
      color: 'success',
      variant: 'card',
      class: {
        root: 'has-data-[state=checked]:border-success',
      },
    } as const,
    {
      color: 'info',
      variant: 'card',
      class: {
        root: 'has-data-[state=checked]:border-info',
      },
    } as const,
    {
      color: 'warning',
      variant: 'card',
      class: {
        root: 'has-data-[state=checked]:border-warning',
      },
    } as const,
    {
      color: 'error',
      variant: 'card',
      class: {
        root: 'has-data-[state=checked]:border-error',
      },
    } as const,
    {
      color: 'neutral',
      variant: 'card',
      class: {
        root: 'has-data-[state=checked]:border-inverted',
      },
    } as const,
    {
      variant: 'card',
      disabled: true,
      class: {
        root: 'cursor-not-allowed opacity-75',
      },
    } as const,
  ],
  defaultVariants: {
    size: 'md',
    color: 'primary',
    variant: 'list',
    indicator: 'start',
  } as const,
}

Test

To test this component, you can use the following test file:

Checkbox.test.ts
ts
import type { RenderOptions } from '@testing-library/vue'
import Checkbox from '@/ui/components/Checkbox.vue'
import theme from '@/ui/theme/checkbox'
import { fireEvent, render, screen } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'

describe('checkbox', () => {
  const sizes = Object.keys(theme.variants.size) as any

  it.each<[string, RenderOptions<typeof Checkbox>]>([
    // Props
    ['with modelValue', { props: { modelValue: true } }],
    ['with defaultValue', { props: { defaultValue: true } }],
    ['with id', { props: { id: 'id' } }],
    ['with name', { props: { name: 'name' } }],
    ['with value', { props: { value: 'value' } }],
    ['with disabled', { props: { disabled: true } }],
    ['with icon', { props: { icon: 'i-lucide-heart' } }],
    ['with indeterminate', { props: { defaultValue: 'indeterminate' } }],
    ['with indeterminateIcon', { props: { defaultValue: 'indeterminate', indeterminateIcon: 'i-lucide-trash' } }],
    ['with label', { props: { label: 'Label' } }],
    ['with required', { props: { label: 'Label', required: true } }],
    ['with description', { props: { label: 'Label', description: 'Description' } }],
    ...sizes.map((size: string) => [`with size ${size}`, { props: { size } }]),
    ['with color neutral', { props: { color: 'neutral', defaultValue: true } }],
    ['with as', { props: { as: 'section' } }],
    ['with class', { props: { class: 'inline-flex' } }],
    ['with ui', { props: { ui: { wrapper: 'ms-4' } } }],
    // Slots
    ['with label slot', { slots: { label: () => 'Label slot' } }],
    ['with description slot', { slots: { label: () => 'Description slot' } }],
  ])('renders %s correctly', (name, options) => {
    const { html } = render(Checkbox, options)

    expect(html()).toMatchSnapshot()
  })

  describe('emits', () => {
    it('update:modelValue event', async () => {
      const { emitted } = render(Checkbox)

      await fireEvent.click(await screen.findByRole('checkbox'))

      expect(emitted()['update:modelValue']).toMatchInlineSnapshot(`
        [
          [
            true,
          ],
        ]
      `)
    })

    it('inverted update:modelValue event', async () => {
      const { emitted } = render(Checkbox, { props: { modelValue: true } })

      await fireEvent.click(await screen.findByRole('checkbox'))

      expect(emitted()['update:modelValue']).toMatchInlineSnapshot(`
        [
          [
            false,
          ],
        ]
      `)
    })
  })
})
Checkbox.test.ts
ts
import type { RenderOptions } from '@testing-library/vue'
import Checkbox from '@/UI/Components/Checkbox.vue'
import theme from '@/UI/Theme/checkbox'
import { fireEvent, render, screen } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'

describe('checkbox', () => {
  const sizes = Object.keys(theme.variants.size) as any

  it.each<[string, RenderOptions<typeof Checkbox>]>([
    // Props
    ['with modelValue', { props: { modelValue: true } }],
    ['with defaultValue', { props: { defaultValue: true } }],
    ['with id', { props: { id: 'id' } }],
    ['with name', { props: { name: 'name' } }],
    ['with value', { props: { value: 'value' } }],
    ['with disabled', { props: { disabled: true } }],
    ['with icon', { props: { icon: 'i-lucide-heart' } }],
    ['with indeterminate', { props: { defaultValue: 'indeterminate' } }],
    ['with indeterminateIcon', { props: { defaultValue: 'indeterminate', indeterminateIcon: 'i-lucide-trash' } }],
    ['with label', { props: { label: 'Label' } }],
    ['with required', { props: { label: 'Label', required: true } }],
    ['with description', { props: { label: 'Label', description: 'Description' } }],
    ...sizes.map((size: string) => [`with size ${size}`, { props: { size } }]),
    ['with color neutral', { props: { color: 'neutral', defaultValue: true } }],
    ['with as', { props: { as: 'section' } }],
    ['with class', { props: { class: 'inline-flex' } }],
    ['with ui', { props: { ui: { wrapper: 'ms-4' } } }],
    // Slots
    ['with label slot', { slots: { label: () => 'Label slot' } }],
    ['with description slot', { slots: { label: () => 'Description slot' } }],
  ])('renders %s correctly', (name, options) => {
    const { html } = render(Checkbox, options)

    expect(html()).toMatchSnapshot()
  })

  describe('emits', () => {
    it('update:modelValue event', async () => {
      const { emitted } = render(Checkbox)

      await fireEvent.click(await screen.findByRole('checkbox'))

      expect(emitted()['update:modelValue']).toMatchInlineSnapshot(`
        [
          [
            true,
          ],
        ]
      `)
    })

    it('inverted update:modelValue event', async () => {
      const { emitted } = render(Checkbox, { props: { modelValue: true } })

      await fireEvent.click(await screen.findByRole('checkbox'))

      expect(emitted()['update:modelValue']).toMatchInlineSnapshot(`
        [
          [
            false,
          ],
        ]
      `)
    })
  })
})

Contributors

barbapapazes

Changelog

7a9f6 - feat: attrs on form elements (#150) on 2/14/2025
c615c - feat: add custom eslint rule to disallow relative imports (#81) on 1/7/2025
d7aca - feat: add checkbox component (#68) on 12/23/2024