Skip to content

Checkbox Group

A set of checklist buttons to select multiple option from a list.

Demo

This requires the following components to be installed:

This requires the following composables to be installed:

This requires the following utils to be installed:

This requires the following types to be installed:

This requires the following theme to be installed:

Component

CheckboxGroup.vue
vue
<script lang="ts">
import type { CheckboxProps } from '@/ui/components/Checkbox.vue'
import type { AcceptableValue, ComponentConfig } from '@/ui/utils/utils'
import type { CheckboxGroupRootEmits, CheckboxGroupRootProps } from 'reka-ui'
import Checkbox from '@/ui/components/Checkbox.vue'
import { useFormField } from '@/ui/composables/useFormField'
import theme from '@/ui/theme/checkbox-group'
import { get } from '@/ui/utils/get'
import { omit } from '@/ui/utils/omit'
import { reactivePick } from '@vueuse/shared'
import { CheckboxGroupRoot, useForwardProps, useForwardPropsEmits } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, useId } from 'vue'

type CheckboxGroup = ComponentConfig<typeof theme>

export type CheckboxGroupValue = AcceptableValue

export type CheckboxGroupItem = {
  label?: string
  description?: string
  disabled?: boolean
  value?: string
  [key: string]: any
} | CheckboxGroupValue

export interface CheckboxGroupProps<T extends CheckboxGroupItem = CheckboxGroupItem> extends Pick<CheckboxGroupRootProps, 'defaultValue' | 'disabled' | 'loop' | 'modelValue' | 'name' | 'required'>, Pick<CheckboxProps, 'color' | 'variant' | 'indicator' | 'icon'> {
  as?: any
  legend?: string
  valueKey?: string
  labelKey?: string
  descriptionKey?: string
  items?: T[]
  size?: CheckboxGroup['variants']['size']
  orientation?: CheckboxGroupRootProps['orientation']
  class?: any
  ui?: CheckboxGroup['slots'] & CheckboxProps['ui']
}

export type CheckboxGroupEmits = CheckboxGroupRootEmits & {
  change: [payload: Event]
}

type SlotProps<T extends CheckboxGroupItem> = (props: { item: T & { id: string } }) => any

export interface CheckboxGroupSlots<T extends CheckboxGroupItem = CheckboxGroupItem> {
  legend: (props?: object) => any
  label: SlotProps<T>
  description: SlotProps<T>
}
</script>

<script setup lang="ts" generic="T extends CheckboxGroupItem">
const props = withDefaults(defineProps<CheckboxGroupProps<T>>(), {
  valueKey: 'value',
  labelKey: 'label',
  descriptionKey: 'description',
  orientation: 'vertical',
})
const emits = defineEmits<CheckboxGroupEmits>()
const slots = defineSlots<CheckboxGroupSlots<T>>()

const rootProps = useForwardPropsEmits(reactivePick(props, 'as', 'modelValue', 'defaultValue', 'orientation', 'loop', 'required'), emits)
const checkboxProps = useForwardProps(reactivePick(props, 'variant', 'indicator', 'icon'))
const proxySlots = omit(slots, ['legend'])

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

const ui = computed(() => tv(theme)({
  size: size.value,
  required: props.required,
  orientation: props.orientation,
}))

function normalizeItem(item: any) {
  if (item === null) {
    return {
      id: `${id}:null`,
      value: undefined,
      label: undefined,
    }
  }

  if (typeof item === 'string' || typeof item === 'number') {
    return {
      id: `${id}:${item}`,
      value: String(item),
      label: String(item),
    }
  }

  const value = get(item, props.valueKey as string)
  const label = get(item, props.labelKey as string)
  const description = get(item, props.descriptionKey as string)

  return {
    ...item,
    value,
    label,
    description,
    id: `${id}:${value}`,
  }
}

const normalizedItems = computed(() => {
  if (!props.items) {
    return []
  }
  return props.items.map(normalizeItem)
})

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>
  <CheckboxGroupRoot
    :id="id"
    v-bind="rootProps"
    :name="name"
    :disabled="disabled"
    :class="ui.root({ class: [props.class, props.ui?.root] })"
    @update:model-value="onUpdate"
  >
    <fieldset :class="ui.fieldset({ class: props.ui?.fieldset })" v-bind="ariaAttrs">
      <legend v-if="legend || !!slots.legend" :class="ui.legend({ class: props.ui?.legend })">
        <slot name="legend">
          {{ legend }}
        </slot>
      </legend>

      <Checkbox
        v-for="item in normalizedItems"
        :key="item.value"
        v-bind="{ ...item, ...checkboxProps }"
        :color="color"
        :size="size"
        :name="name"
        :disabled="item.disabled || disabled"
        :ui="props.ui ? omit(props.ui, ['root']) : undefined"
        :class="ui.item({ class: props.ui?.item })"
      >
        <template v-for="(_, name) in proxySlots" #[name]>
          <slot :name="(name as keyof CheckboxGroupSlots<T>)" :item="item" />
        </template>
      </Checkbox>
    </fieldset>
  </CheckboxGroupRoot>
</template>
CheckboxGroup.vue
vue
<script lang="ts">
import type { CheckboxProps } from '@/UI/Components/Checkbox.vue'
import type { AcceptableValue, ComponentConfig } from '@/UI/Utils/utils'
import type { CheckboxGroupRootEmits, CheckboxGroupRootProps } from 'reka-ui'
import Checkbox from '@/UI/Components/Checkbox.vue'
import { useFormField } from '@/UI/Composables/useFormField'
import theme from '@/UI/Theme/checkbox-group'
import { get } from '@/UI/Utils/get'
import { omit } from '@/UI/Utils/omit'
import { reactivePick } from '@vueuse/shared'
import { CheckboxGroupRoot, useForwardProps, useForwardPropsEmits } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, useId } from 'vue'

type CheckboxGroup = ComponentConfig<typeof theme>

export type CheckboxGroupValue = AcceptableValue

export type CheckboxGroupItem = {
  label?: string
  description?: string
  disabled?: boolean
  value?: string
  [key: string]: any
} | CheckboxGroupValue

export interface CheckboxGroupProps<T extends CheckboxGroupItem = CheckboxGroupItem> extends Pick<CheckboxGroupRootProps, 'defaultValue' | 'disabled' | 'loop' | 'modelValue' | 'name' | 'required'>, Pick<CheckboxProps, 'color' | 'variant' | 'indicator' | 'icon'> {
  as?: any
  legend?: string
  valueKey?: string
  labelKey?: string
  descriptionKey?: string
  items?: T[]
  size?: CheckboxGroup['variants']['size']
  orientation?: CheckboxGroupRootProps['orientation']
  class?: any
  ui?: CheckboxGroup['slots'] & CheckboxProps['ui']
}

export type CheckboxGroupEmits = CheckboxGroupRootEmits & {
  change: [payload: Event]
}

type SlotProps<T extends CheckboxGroupItem> = (props: { item: T & { id: string } }) => any

export interface CheckboxGroupSlots<T extends CheckboxGroupItem = CheckboxGroupItem> {
  legend: (props?: object) => any
  label: SlotProps<T>
  description: SlotProps<T>
}
</script>

<script setup lang="ts" generic="T extends CheckboxGroupItem">
const props = withDefaults(defineProps<CheckboxGroupProps<T>>(), {
  valueKey: 'value',
  labelKey: 'label',
  descriptionKey: 'description',
  orientation: 'vertical',
})
const emits = defineEmits<CheckboxGroupEmits>()
const slots = defineSlots<CheckboxGroupSlots<T>>()

const rootProps = useForwardPropsEmits(reactivePick(props, 'as', 'modelValue', 'defaultValue', 'orientation', 'loop', 'required'), emits)
const checkboxProps = useForwardProps(reactivePick(props, 'variant', 'indicator', 'icon'))
const proxySlots = omit(slots, ['legend'])

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

const ui = computed(() => tv(theme)({
  size: size.value,
  required: props.required,
  orientation: props.orientation,
}))

function normalizeItem(item: any) {
  if (item === null) {
    return {
      id: `${id}:null`,
      value: undefined,
      label: undefined,
    }
  }

  if (typeof item === 'string' || typeof item === 'number') {
    return {
      id: `${id}:${item}`,
      value: String(item),
      label: String(item),
    }
  }

  const value = get(item, props.valueKey as string)
  const label = get(item, props.labelKey as string)
  const description = get(item, props.descriptionKey as string)

  return {
    ...item,
    value,
    label,
    description,
    id: `${id}:${value}`,
  }
}

const normalizedItems = computed(() => {
  if (!props.items) {
    return []
  }
  return props.items.map(normalizeItem)
})

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>
  <CheckboxGroupRoot
    :id="id"
    v-bind="rootProps"
    :name="name"
    :disabled="disabled"
    :class="ui.root({ class: [props.class, props.ui?.root] })"
    @update:model-value="onUpdate"
  >
    <fieldset :class="ui.fieldset({ class: props.ui?.fieldset })" v-bind="ariaAttrs">
      <legend v-if="legend || !!slots.legend" :class="ui.legend({ class: props.ui?.legend })">
        <slot name="legend">
          {{ legend }}
        </slot>
      </legend>

      <Checkbox
        v-for="item in normalizedItems"
        :key="item.value"
        v-bind="{ ...item, ...checkboxProps }"
        :color="color"
        :size="size"
        :name="name"
        :disabled="item.disabled || disabled"
        :ui="props.ui ? omit(props.ui, ['root']) : undefined"
        :class="ui.item({ class: props.ui?.item })"
      >
        <template v-for="(_, name) in proxySlots" #[name]>
          <slot :name="(name as keyof CheckboxGroupSlots<T>)" :item="item" />
        </template>
      </Checkbox>
    </fieldset>
  </CheckboxGroupRoot>
</template>

Theme

checkbox-group.ts
ts
export default {
  slots: {
    root: '',
    fieldset: '',
    legend: '',
    item: '',
  },
  variants: {
    orientation: {
      horizontal: {
        fieldset: '',
      },
      vertical: {
        fieldset: '',
      },
    },
    size: {
      xs: {
        fieldset: '',
        legend: '',
      },
      sm: {
        fieldset: '',
        legend: '',
      },
      md: {
        fieldset: '',
        legend: '',
      },
      lg: {
        fieldset: '',
        legend: '',
      },
      xl: {
        fieldset: '',
        legend: '',
      },
    },
    required: {
      true: {
        legend: '',
      },
    },
  },
  defaultVariants: {
    size: 'md',
  } as const,
}
View Nuxt UI theme
checkbox-group.ts
ts
export default {
  slots: {
    root: 'relative',
    fieldset: 'flex gap-x-2',
    legend: 'mb-1 block font-medium text-default',
    item: '',
  },
  variants: {
    orientation: {
      horizontal: {
        fieldset: 'flex-row',
      },
      vertical: {
        fieldset: 'flex-col',
      },
    },
    size: {
      xs: {
        fieldset: 'gap-y-0.5',
        legend: 'text-xs',
      },
      sm: {
        fieldset: 'gap-y-0.5',
        legend: 'text-xs',
      },
      md: {
        fieldset: 'gap-y-1',
        legend: 'text-sm',
      },
      lg: {
        fieldset: 'gap-y-1',
        legend: 'text-sm',
      },
      xl: {
        fieldset: 'gap-y-1.5',
        legend: 'text-base',
      },
    },
    required: {
      true: {
        legend: 'after:content-[\'*\'] after:ms-0.5 after:text-error',
      },
    },
  },
  defaultVariants: {
    size: 'md',
  } as const,
}

Test

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

CheckboxGroup.test.ts
ts
import CheckboxGroup from '@/ui/components/CheckboxGroup.vue'
import themeCheckbox from '@/ui/theme/checkbox'
import theme from '@/ui/theme/checkbox-group'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'

describe('checkboxGroup', () => {
  const sizes = Object.keys(theme.variants.size) as any
  const variants = Object.keys(themeCheckbox.variants.variant) as any
  const indicators = Object.keys(themeCheckbox.variants.indicator) as any

  const items = [
    { value: '1', label: 'Option 1' },
    { value: '2', label: 'Option 2' },
    { value: '3', label: 'Option 3' },
  ]

  const props = { items }

  it.each([
    ['with items', { props }],
    ['with modelValue', { props: { ...props, modelValue: ['1'] } }],
    ['with defaultValue', { props: { ...props, defaultValue: ['1'] } }],
    ['with valueKey', { props: { ...props, valueKey: 'label' } }],
    ['with labelKey', { props: { ...props, labelKey: 'value' } }],
    ['with descriptionKey', { props: { ...props, descriptionKey: 'value' } }],
    ['with disabled', { props: { ...props, disabled: true } }],
    ['with description', { props: { items: items.map((opt, count) => ({ ...opt, description: `Description ${count}` })) } }],
    ['with required', { props: { ...props, legend: 'Legend', required: true } }],
    ...sizes.map((size: string) => [`with size ${size}`, { props: { ...props, size, defaultValue: ['1'] } }]),
    ...variants.map((variant: string) => [`with primary variant ${variant}`, { props: { ...props, variant, defaultValue: ['1'] } }]),
    ...variants.map((variant: string) => [`with neutral variant ${variant}`, { props: { ...props, variant, color: 'neutral', defaultValue: ['1'] } }]),
    ...variants.map((variant: string) => [`with horizontal variant ${variant}`, { props: { ...props, variant, orientation: 'horizontal', defaultValue: ['1'] } }]),
    ...indicators.map((indicator: string) => [`with indicator ${indicator}`, { props: { ...props, indicator, defaultValue: ['1'] } }]),
    ['with ariaLabel', { props, attrs: { 'aria-label': 'Aria label' } }],
    ['with as', { props: { ...props, as: 'section' } }],
    ['with class', { props: { ...props, class: 'absolute' } }],
    ['with ui', { props: { ...props, ui: { fieldset: 'gap-x-4', label: 'text-red' } } }],
    // Slots
    ['with legend slot', { props, slots: { legend: () => 'Legend slot' } }],
    ['with label slot', { props, slots: { label: () => 'Label slot' } }],
    ['with description slot', { props, slots: { description: () => 'Description slot' } }],
  ])('renders %s correctly', (name, options) => {
    const { html } = render(CheckboxGroup, options)

    expect(html()).toMatchSnapshot()
  })
})
CheckboxGroup.test.ts
ts
import CheckboxGroup from '@/UI/Components/CheckboxGroup.vue'
import themeCheckbox from '@/UI/Theme/checkbox'
import theme from '@/UI/Theme/checkbox-group'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'

describe('checkboxGroup', () => {
  const sizes = Object.keys(theme.variants.size) as any
  const variants = Object.keys(themeCheckbox.variants.variant) as any
  const indicators = Object.keys(themeCheckbox.variants.indicator) as any

  const items = [
    { value: '1', label: 'Option 1' },
    { value: '2', label: 'Option 2' },
    { value: '3', label: 'Option 3' },
  ]

  const props = { items }

  it.each([
    ['with items', { props }],
    ['with modelValue', { props: { ...props, modelValue: ['1'] } }],
    ['with defaultValue', { props: { ...props, defaultValue: ['1'] } }],
    ['with valueKey', { props: { ...props, valueKey: 'label' } }],
    ['with labelKey', { props: { ...props, labelKey: 'value' } }],
    ['with descriptionKey', { props: { ...props, descriptionKey: 'value' } }],
    ['with disabled', { props: { ...props, disabled: true } }],
    ['with description', { props: { items: items.map((opt, count) => ({ ...opt, description: `Description ${count}` })) } }],
    ['with required', { props: { ...props, legend: 'Legend', required: true } }],
    ...sizes.map((size: string) => [`with size ${size}`, { props: { ...props, size, defaultValue: ['1'] } }]),
    ...variants.map((variant: string) => [`with primary variant ${variant}`, { props: { ...props, variant, defaultValue: ['1'] } }]),
    ...variants.map((variant: string) => [`with neutral variant ${variant}`, { props: { ...props, variant, color: 'neutral', defaultValue: ['1'] } }]),
    ...variants.map((variant: string) => [`with horizontal variant ${variant}`, { props: { ...props, variant, orientation: 'horizontal', defaultValue: ['1'] } }]),
    ...indicators.map((indicator: string) => [`with indicator ${indicator}`, { props: { ...props, indicator, defaultValue: ['1'] } }]),
    ['with ariaLabel', { props, attrs: { 'aria-label': 'Aria label' } }],
    ['with as', { props: { ...props, as: 'section' } }],
    ['with class', { props: { ...props, class: 'absolute' } }],
    ['with ui', { props: { ...props, ui: { fieldset: 'gap-x-4', label: 'text-red' } } }],
    // Slots
    ['with legend slot', { props, slots: { legend: () => 'Legend slot' } }],
    ['with label slot', { props, slots: { label: () => 'Label slot' } }],
    ['with description slot', { props, slots: { description: () => 'Description slot' } }],
  ])('renders %s correctly', (name, options) => {
    const { html } = render(CheckboxGroup, options)

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

Contributors

barbapapazes

Changelog

99dc2 - feat: checkbox group on 4/25/2025