RadioGroup
A set of radio buttons to select a single option from a list.
Demo
Related Composables
This requires the following composables to be installed:
Related Utils
This requires the following utils to be installed:
Related Types
This requires the following types to be installed:
Related Theme
This requires the following theme to be installed:
Component
vue
<script lang="ts">
import type { AcceptableValue, ComponentConfig } from '@/ui/utils/utils'
import type { RadioGroupRootEmits, RadioGroupRootProps } from 'reka-ui'
import { useFormField } from '@/ui/composables/useFormField'
import theme from '@/ui/theme/radio-group'
import { get } from '@/ui/utils/get'
import { reactivePick } from '@vueuse/shared'
import { Label, RadioGroupIndicator, RadioGroupRoot, RadioGroupItem as RekaRadiopGroupItem, useForwardPropsEmits } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, useId } from 'vue'
type RadioGroup = ComponentConfig<typeof theme>
export type RadioGroupValue = AcceptableValue
export type RadioGroupItem = {
label?: string
description?: string
disabled?: boolean
value?: string
[key: string]: any
} | RadioGroupValue
export interface RadioGroupProps<T extends RadioGroupItem = RadioGroupItem> extends Pick<RadioGroupRootProps, 'defaultValue' | 'disabled' | 'loop' | 'modelValue' | 'name' | 'required'> {
as?: any
legend?: string
valueKey?: string
labelKey?: string
descriptionKey?: string
items?: T[]
size?: RadioGroup['variants']['size']
variant?: RadioGroup['variants']['variant']
color?: RadioGroup['variants']['color']
orientation?: RadioGroupRootProps['orientation']
indicator?: RadioGroup['variants']['indicator']
class?: any
ui?: RadioGroup['slots']
}
export type RadioGroupEmits = RadioGroupRootEmits & {
change: [payload: Event]
}
type SlotProps<T extends RadioGroupItem> = (props: { item: T & { id: string }, modelValue?: RadioGroupValue }) => any
export interface RadioGroupSlots<T extends RadioGroupItem = RadioGroupItem> {
legend: (props?: object) => any
label: SlotProps<T>
description: SlotProps<T>
}
</script>
<script setup lang="ts" generic="T extends RadioGroupItem">
const props = withDefaults(defineProps<RadioGroupProps<T>>(), {
valueKey: 'value',
labelKey: 'label',
descriptionKey: 'description',
orientation: 'vertical',
})
const emits = defineEmits<RadioGroupEmits>()
const slots = defineSlots<RadioGroupSlots<T>>()
const rootProps = useForwardPropsEmits(reactivePick(props, 'as', 'modelValue', 'defaultValue', 'orientation', 'loop', 'required'), emits)
const { color, name, size, id: _id, disabled, ariaAttrs } = useFormField<RadioGroupProps<T>>(props, { bind: false })
const id = _id.value ?? useId()
const ui = computed(() => tv(theme)({
size: size.value,
color: color.value,
disabled: disabled.value,
required: props.required,
orientation: props.orientation,
variant: props.variant,
indicator: props.indicator,
}))
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>
<template>
<RadioGroupRoot
:id="id"
v-slot="{ modelValue }"
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>
<component :is="variant === 'list' ? 'div' : Label" v-for="item in normalizedItems" :key="item.value" :class="ui.item({ class: props.ui?.item })">
<div :class="ui.container({ class: props.ui?.container })">
<RekaRadiopGroupItem
:id="item.id"
:value="item.value"
:disabled="item.disabled"
:class="ui.base({ class: props.ui?.base, disabled: item.disabled })"
>
<RadioGroupIndicator :class="ui.indicator({ class: props.ui?.indicator })" />
</RekaRadiopGroupItem>
</div>
<div v-if="(item.label || !!slots.label) || (item.description || !!slots.description)" :class="ui.wrapper({ class: props.ui?.wrapper })">
<component :is="variant === 'list' ? Label : 'p'" v-if="item.label || !!slots.label" :for="item.id" :class="ui.label({ class: props.ui?.label })">
<slot name="label" :item="item" :model-value="(modelValue as RadioGroupValue)">
{{ item.label }}
</slot>
</component>
<p v-if="item.description || !!slots.description" :class="ui.description({ class: props.ui?.description })">
<slot name="description" :item="item" :model-value="(modelValue as RadioGroupValue)">
{{ item.description }}
</slot>
</p>
</div>
</component>
</fieldset>
</RadioGroupRoot>
</template>vue
<script lang="ts">
import type { AcceptableValue, ComponentConfig } from '@/UI/Utils/utils'
import type { RadioGroupRootEmits, RadioGroupRootProps } from 'reka-ui'
import { useFormField } from '@/UI/Composables/useFormField'
import theme from '@/UI/Theme/radio-group'
import { get } from '@/UI/Utils/get'
import { reactivePick } from '@vueuse/shared'
import { Label, RadioGroupIndicator, RadioGroupRoot, RadioGroupItem as RekaRadiopGroupItem, useForwardPropsEmits } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, useId } from 'vue'
type RadioGroup = ComponentConfig<typeof theme>
export type RadioGroupValue = AcceptableValue
export type RadioGroupItem = {
label?: string
description?: string
disabled?: boolean
value?: string
[key: string]: any
} | RadioGroupValue
export interface RadioGroupProps<T extends RadioGroupItem = RadioGroupItem> extends Pick<RadioGroupRootProps, 'defaultValue' | 'disabled' | 'loop' | 'modelValue' | 'name' | 'required'> {
as?: any
legend?: string
valueKey?: string
labelKey?: string
descriptionKey?: string
items?: T[]
size?: RadioGroup['variants']['size']
variant?: RadioGroup['variants']['variant']
color?: RadioGroup['variants']['color']
orientation?: RadioGroupRootProps['orientation']
indicator?: RadioGroup['variants']['indicator']
class?: any
ui?: RadioGroup['slots']
}
export type RadioGroupEmits = RadioGroupRootEmits & {
change: [payload: Event]
}
type SlotProps<T extends RadioGroupItem> = (props: { item: T & { id: string }, modelValue?: RadioGroupValue }) => any
export interface RadioGroupSlots<T extends RadioGroupItem = RadioGroupItem> {
legend: (props?: object) => any
label: SlotProps<T>
description: SlotProps<T>
}
</script>
<script setup lang="ts" generic="T extends RadioGroupItem">
const props = withDefaults(defineProps<RadioGroupProps<T>>(), {
valueKey: 'value',
labelKey: 'label',
descriptionKey: 'description',
orientation: 'vertical',
})
const emits = defineEmits<RadioGroupEmits>()
const slots = defineSlots<RadioGroupSlots<T>>()
const rootProps = useForwardPropsEmits(reactivePick(props, 'as', 'modelValue', 'defaultValue', 'orientation', 'loop', 'required'), emits)
const { color, name, size, id: _id, disabled, ariaAttrs } = useFormField<RadioGroupProps<T>>(props, { bind: false })
const id = _id.value ?? useId()
const ui = computed(() => tv(theme)({
size: size.value,
color: color.value,
disabled: disabled.value,
required: props.required,
orientation: props.orientation,
variant: props.variant,
indicator: props.indicator,
}))
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>
<template>
<RadioGroupRoot
:id="id"
v-slot="{ modelValue }"
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>
<component :is="variant === 'list' ? 'div' : Label" v-for="item in normalizedItems" :key="item.value" :class="ui.item({ class: props.ui?.item })">
<div :class="ui.container({ class: props.ui?.container })">
<RekaRadiopGroupItem
:id="item.id"
:value="item.value"
:disabled="item.disabled"
:class="ui.base({ class: props.ui?.base, disabled: item.disabled })"
>
<RadioGroupIndicator :class="ui.indicator({ class: props.ui?.indicator })" />
</RekaRadiopGroupItem>
</div>
<div v-if="(item.label || !!slots.label) || (item.description || !!slots.description)" :class="ui.wrapper({ class: props.ui?.wrapper })">
<component :is="variant === 'list' ? Label : 'p'" v-if="item.label || !!slots.label" :for="item.id" :class="ui.label({ class: props.ui?.label })">
<slot name="label" :item="item" :model-value="(modelValue as RadioGroupValue)">
{{ item.label }}
</slot>
</component>
<p v-if="item.description || !!slots.description" :class="ui.description({ class: props.ui?.description })">
<slot name="description" :item="item" :model-value="(modelValue as RadioGroupValue)">
{{ item.description }}
</slot>
</p>
</div>
</component>
</fieldset>
</RadioGroupRoot>
</template>Theme
ts
export default {
slots: {
root: '',
fieldset: '',
legend: '',
item: '',
container: '',
base: '',
indicator: '',
wrapper: '',
label: '',
description: '',
},
variants: {
color: {
primary: {
base: '',
indicator: '',
},
secondary: {
base: '',
indicator: '',
},
success: {
base: '',
indicator: '',
},
error: {
base: '',
indicator: '',
},
warning: {
base: '',
indicator: '',
},
info: {
base: '',
indicator: '',
},
neutral: {
base: '',
indicator: '',
},
},
variant: {
list: {
item: '',
},
card: {
item: '',
},
table: {
item: '',
},
},
orientation: {
horizontal: {
fieldset: '',
},
vertical: {
fieldset: '',
},
},
indicator: {
start: {
item: '',
wrapper: '',
},
end: {
item: '',
wrapper: '',
},
hidden: {
base: '',
wrapper: '',
},
},
size: {
xs: {
fieldset: '',
legend: '',
base: '',
item: '',
container: '',
indicator: '',
},
sm: {
fieldset: '',
legend: '',
base: '',
item: '',
container: '',
indicator: '',
},
md: {
fieldset: '',
legend: '',
base: '',
item: '',
container: '',
indicator: '',
},
lg: {
fieldset: '',
legend: '',
base: '',
item: '',
container: '',
indicator: '',
},
xl: {
fieldset: '',
legend: '',
base: '',
item: '',
container: '',
indicator: '',
},
},
disabled: {
true: {
base: '',
label: '',
},
},
required: {
true: {
legend: '',
},
},
},
compoundVariants: [],
defaultVariants: {
size: 'md',
color: 'primary',
variant: 'list',
orientation: 'vertical',
indicator: 'start',
} as const,
}View Nuxt UI theme
ts
export default {
slots: {
root: 'relative',
fieldset: 'flex gap-x-2',
legend: 'mb-1 block font-medium text-default',
item: 'flex items-start',
container: 'flex items-center',
base: 'rounded-full ring ring-inset ring-accented overflow-hidden focus-visible:outline-2 focus-visible:outline-offset-2',
indicator: 'flex items-center justify-center size-full after:bg-default after:rounded-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',
},
error: {
base: 'focus-visible:outline-error',
indicator: 'bg-error',
},
warning: {
base: 'focus-visible:outline-warning',
indicator: 'bg-warning',
},
info: {
base: 'focus-visible:outline-info',
indicator: 'bg-info',
},
neutral: {
base: 'focus-visible:outline-inverted',
indicator: 'bg-inverted',
},
},
variant: {
list: {
item: '',
},
card: {
item: 'border border-muted rounded-lg',
},
table: {
item: 'border border-muted',
},
},
orientation: {
horizontal: {
fieldset: 'flex-row',
},
vertical: {
fieldset: 'flex-col',
},
},
indicator: {
start: {
item: 'flex-row',
wrapper: 'ms-2',
},
end: {
item: 'flex-row-reverse',
wrapper: 'me-2',
},
hidden: {
base: 'sr-only',
wrapper: 'text-center',
},
},
size: {
xs: {
fieldset: 'gap-y-0.5',
legend: 'text-xs',
base: 'size-3',
item: 'text-xs',
container: 'h-4',
indicator: 'after:size-1',
},
sm: {
fieldset: 'gap-y-0.5',
legend: 'text-xs',
base: 'size-3.5',
item: 'text-xs',
container: 'h-4',
indicator: 'after:size-1',
},
md: {
fieldset: 'gap-y-1',
legend: 'text-sm',
base: 'size-4',
item: 'text-sm',
container: 'h-5',
indicator: 'after:size-1.5',
},
lg: {
fieldset: 'gap-y-1',
legend: 'text-sm',
base: 'size-4.5',
item: 'text-sm',
container: 'h-5',
indicator: 'after:size-1.5',
},
xl: {
fieldset: 'gap-y-1.5',
legend: 'text-base',
base: 'size-5',
item: 'text-base',
container: 'h-6',
indicator: 'after:size-2',
},
},
disabled: {
true: {
base: 'cursor-not-allowed opacity-75',
label: 'cursor-not-allowed opacity-75',
},
},
required: {
true: {
legend: 'after:content-[\'*\'] after:ms-0.5 after:text-error',
},
},
},
compoundVariants: [
{
size: 'xs' as const,
variant: ['card' as const, 'table' as const],
class: { item: 'p-2.5' },
},
{
size: 'sm' as const,
variant: ['card' as const, 'table' as const],
class: { item: 'p-3' },
},
{
size: 'md' as const,
variant: ['card' as const, 'table' as const],
class: { item: 'p-3.5' },
},
{
size: 'lg' as const,
variant: ['card' as const, 'table' as const],
class: { item: 'p-4' },
},
{
size: 'xl' as const,
variant: ['card' as const, 'table' as const],
class: { item: 'p-4.5' },
},
{
orientation: 'horizontal',
variant: 'table',
class: {
item: 'first-of-type:rounded-l-lg last-of-type:rounded-r-lg',
fieldset: 'gap-0 -space-x-px',
},
} as const,
{
orientation: 'vertical',
variant: 'table',
class: {
item: 'first-of-type:rounded-t-lg last-of-type:rounded-b-lg',
fieldset: 'gap-0 -space-y-px',
},
} as const,
{
color: 'primary',
variant: 'card',
class: {
item: `has-data-[state=checked]:border-primary`,
},
} as const,
{
color: 'secondary',
variant: 'card',
class: {
item: 'has-data-[state=checked]:border-secondary',
},
} as const,
{
color: 'success',
variant: 'card',
class: {
item: 'has-data-[state=checked]:border-success',
},
} as const,
{
color: 'error',
variant: 'card',
class: {
item: 'has-data-[state=checked]:border-error',
},
} as const,
{
color: 'warning',
variant: 'card',
class: {
item: 'has-data-[state=checked]:border-warning',
},
} as const,
{
color: 'info',
variant: 'card',
class: {
item: 'has-data-[state=checked]:border-info',
},
} as const,
{
color: 'neutral',
variant: 'card',
class: {
item: 'has-data-[state=checked]:border-inverted',
},
} as const,
{
color: 'primary',
variant: 'table',
class: {
item: `has-data-[state=checked]:bg-primary/10 has-data-[state=checked]:border-primary/50 has-data-[state=checked]:z-[1]`,
},
} as const,
{
color: 'secondary',
variant: 'table',
class: {
item: `has-data-[state=checked]:bg-secondary/10 has-data-[state=checked]:border-secondary/50 has-data-[state=checked]:z-[1]`,
},
} as const,
{
color: 'success',
variant: 'table',
class: {
item: `has-data-[state=checked]:bg-success/10 has-data-[state=checked]:border-success/50 has-data-[state=checked]:z-[1]`,
},
} as const,
{
color: 'info',
variant: 'table',
class: {
item: `has-data-[state=checked]:bg-info/10 has-data-[state=checked]:border-info/50 has-data-[state=checked]:z-[1]`,
},
} as const,
{
color: 'error',
variant: 'table',
class: {
item: `has-data-[state=checked]:bg-error/10 has-data-[state=checked]:border-error/50 has-data-[state=checked]:z-[1]`,
},
} as const,
{
color: 'warning',
variant: 'table',
class: {
item: `has-data-[state=checked]:bg-warning/10 has-data-[state=checked]:border-warning/50 has-data-[state=checked]:z-[1]`,
},
} as const,
{
color: 'neutral',
variant: 'table',
class: {
item: 'has-data-[state=checked]:bg-elevated has-data-[state=checked]:border-inverted/50 has-data-[state=checked]:z-[1]',
},
} as const,
{
variant: ['card' as const, 'table' as const],
disabled: true,
class: {
item: 'cursor-not-allowed opacity-75',
},
},
],
defaultVariants: {
size: 'md',
color: 'primary',
variant: 'list',
orientation: 'vertical',
indicator: 'start',
} as const,
}Test
To test this component, you can use the following test file:
ts
import type { RenderOptions } from '@testing-library/vue'
import RadioGroup from '@/ui/components/RadioGroup.vue'
import theme from '@/ui/theme/radio-group'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'
describe('radioGroup', () => {
const sizes = Object.keys(theme.variants.size) as any
const variants = Object.keys(theme.variants.variant) as any
const indicators = Object.keys(theme.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<[string, RenderOptions<typeof RadioGroup>]>([
['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: { wrapper: 'ms-4' } } }],
// Slots
['with legend slot', { props, slots: { label: () => 'Legend slot' } }],
['with label slot', { props, slots: { label: () => 'Label slot' } }],
['with description slot', { props, slots: { label: () => 'Description slot' } }],
])('renders %s correctly', (name, options) => {
const { html } = render(RadioGroup, options)
expect(html()).toMatchSnapshot()
})
})ts
import type { RenderOptions } from '@testing-library/vue'
import RadioGroup from '@/UI/Components/RadioGroup.vue'
import theme from '@/UI/Theme/radio-group'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'
describe('radioGroup', () => {
const sizes = Object.keys(theme.variants.size) as any
const variants = Object.keys(theme.variants.variant) as any
const indicators = Object.keys(theme.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<[string, RenderOptions<typeof RadioGroup>]>([
['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: { wrapper: 'ms-4' } } }],
// Slots
['with legend slot', { props, slots: { label: () => 'Legend slot' } }],
['with label slot', { props, slots: { label: () => 'Label slot' } }],
['with description slot', { props, slots: { label: () => 'Description slot' } }],
])('renders %s correctly', (name, options) => {
const { html } = render(RadioGroup, options)
expect(html()).toMatchSnapshot()
})
})