RadioGroup
A controlled group of radio buttons with roving focus and arrow-key picking.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RadioGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { RadioGroupIndicator, RadioGroupLabel, RadioGroupRadio, RadioGroupRoot } from "#ui/radio-group"
const RadioGroupBasicMessage = UiSchema.TaggedEnum({ PickedDensity: { value: Schema.String } })
const densities = [
{ value: "default", label: "Default" },
{ value: "comfortable", label: "Comfortable" },
{ value: "compact", label: "Compact" }
]
export const RadioGroupBasic = Html.component({
name: "RadioGroupBasic",
model: Schema.Struct({ density: Schema.NullOr(Schema.String) }),
message: RadioGroupBasicMessage
}).make({
init: () => ({ density: "comfortable" }),
update: {
PickedDensity: ($, { value }) => $.evolve({ density: value })
},
view: (h, model) =>
RadioGroup(h, {
props: { value: model.density, items: densities.map(({ value }) => ({ value })) },
onEmit: { Picked: ({ value }) => RadioGroupBasicMessage.PickedDensity({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup).attr("aria-label", "Density").children(
densities.map(({ label, value }) =>
RadioGroupLabel(h).children(
RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value })),
label
)
)
)
})
})
Installation
Set up the project
Once per project: the packages, Tailwind CSS, the theme tokens and the
cnhelper. Follow Installation.Copy the component into your project
The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
src/ui/radio-group.ts import type { Component } from "@effect/ui" import type { Html } from "@effect/ui/html" import type { RadioGroup } from "@effect/ui-kit" import { cn } from "#lib/cn" type RadioGroupParts = Component.Headless.Parts<typeof RadioGroup> interface ClassOption { readonly class?: string | undefined } const orientations = { vertical: "grid gap-2.5", horizontal: "flex flex-wrap items-center gap-x-5 gap-y-2" } as const /** The group. The arrow keys move and pick in both layouts. */ export const RadioGroupRoot = <Msg>( h: Html.H<Msg>, radioGroup: RadioGroupParts, options: ClassOption & { readonly orientation?: keyof typeof orientations | undefined } = {} ) => radioGroup.root( h.div.class(cn("group/radio-group min-w-0", orientations[options.orientation ?? "vertical"], options.class)) ) /** * One radio, for the `value` of an entry in the group's `items` prop. Put its * indicator in it: `RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value }))`. */ export const RadioGroupRadio = <Msg>( h: Html.H<Msg>, radioGroup: RadioGroupParts, options: ClassOption & { readonly value: string } ) => radioGroup.radio({ element: h.button.class(cn( "inline-grid size-4 shrink-0 place-items-center rounded-full border border-input bg-background p-0 shadow-sm " + "transition-colors duration-150 hover:border-muted-foreground data-[checked]:border-brand " + "data-[readonly]:cursor-default data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 " + "group-aria-[invalid=true]/radio-group:border-destructive", options.class )), value: options.value }) /** The dot. The kit keeps it mounted for one transition after its radio is unchecked, so it scales out. */ export const RadioGroupIndicator = <Msg>( h: Html.H<Msg>, radioGroup: RadioGroupParts, options: ClassOption & { readonly value: string } ) => radioGroup.indicator({ element: h.span.class(cn( "size-2 rounded-full bg-brand transition-[scale] duration-150 " + "data-[starting-style]:scale-0 data-[ending-style]:scale-0", options.class )), value: options.value }) /** The group's name. Give it an `id` and point the root's `aria-labelledby` at it. */ export const RadioGroupLegend = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) => h.div.class(cn("text-[13px] leading-5 font-medium", options.class)) /** A label for one radio: around it, or beside it with `for`. It dims with a disabled radio inside it. */ export const RadioGroupLabel = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) => h.label.class(cn( "inline-flex cursor-pointer items-center gap-2 text-[13px] leading-4 select-none " + "has-[[data-disabled]]:cursor-not-allowed has-[[data-disabled]]:text-muted-foreground", options.class ))Import it
import { RadioGroupRoot, RadioGroupRadio, RadioGroupIndicator, RadioGroupLegend, RadioGroupLabel } from "#ui/radio-group"
Usage
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RadioGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { RadioGroupIndicator, RadioGroupLabel, RadioGroupRadio, RadioGroupRoot } from "#ui/radio-group"
const RadioGroupBasicMessage = UiSchema.TaggedEnum({ PickedDensity: { value: Schema.String } })
const densities = [
{ value: "default", label: "Default" },
{ value: "comfortable", label: "Comfortable" },
{ value: "compact", label: "Compact" }
]
export const RadioGroupBasic = Html.component({
name: "RadioGroupBasic",
model: Schema.Struct({ density: Schema.NullOr(Schema.String) }),
message: RadioGroupBasicMessage
}).make({
init: () => ({ density: "comfortable" }),
update: {
PickedDensity: ($, { value }) => $.evolve({ density: value })
},
view: (h, model) =>
RadioGroup(h, {
props: { value: model.density, items: densities.map(({ value }) => ({ value })) },
onEmit: { Picked: ({ value }) => RadioGroupBasicMessage.PickedDensity({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup).attr("aria-label", "Density").children(
densities.map(({ label, value }) =>
RadioGroupLabel(h).children(
RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value })),
label
)
)
)
})
})
Examples
With descriptions
Each radio has a label that points at its id, and a description beside it.
Every comment, mention and status change.
Only when someone mentions you by name.
You can still see activity in the inbox.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RadioGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { RadioGroupIndicator, RadioGroupLabel, RadioGroupLegend, RadioGroupRadio, RadioGroupRoot } from "#ui/radio-group"
const RadioGroupDescriptionsMessage = UiSchema.TaggedEnum({ PickedNotify: { value: Schema.String } })
const options = [
{ value: "all", label: "All activity", description: "Every comment, mention and status change." },
{ value: "mentions", label: "Mentions only", description: "Only when someone mentions you by name." },
{ value: "none", label: "Nothing", description: "You can still see activity in the inbox." }
]
export const RadioGroupDescriptions = Html.component({
name: "RadioGroupDescriptions",
model: Schema.Struct({ notify: Schema.NullOr(Schema.String) }),
message: RadioGroupDescriptionsMessage
}).make({
init: () => ({ notify: "mentions" }),
update: {
PickedNotify: ($, { value }) => $.evolve({ notify: value })
},
view: (h, model) =>
RadioGroup(h, {
props: { value: model.notify, items: options.map(({ value }) => ({ value })) },
onEmit: { Picked: ({ value }) => RadioGroupDescriptionsMessage.PickedNotify({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup).attr("aria-labelledby", "radio-group-notify")
.children(
RadioGroupLegend(h).attr("id", "radio-group-notify").children("Notify me about"),
options.map(({ description, label, value }) =>
h.div.class("flex max-w-xs items-start gap-2.5").children(
RadioGroupRadio(h, radioGroup, { value })
.attrs({ id: `radio-group-notify-${value}`, "aria-describedby": `radio-group-notify-${value}-description` })
.children(RadioGroupIndicator(h, radioGroup, { value })),
h.div.class("grid gap-1").children(
RadioGroupLabel(h, { class: "font-medium" }).attr("for", `radio-group-notify-${value}`).children(label),
h.p
.class("text-[13px] text-muted-foreground")
.attr("id", `radio-group-notify-${value}-description`)
.children(description)
)
)
)
)
})
})
Cards
Each card is the label, filled while the radio inside it is picked.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RadioGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { RadioGroupIndicator, RadioGroupRadio, RadioGroupRoot } from "#ui/radio-group"
const RadioGroupCardsMessage = UiSchema.TaggedEnum({ PickedPlan: { value: Schema.String } })
const plans = [
{ value: "hobby", label: "Hobby", price: "$0", description: "One project, community support." },
{ value: "pro", label: "Pro", price: "$20", description: "Unlimited projects and previews." },
{ value: "team", label: "Team", price: "$60", description: "Roles, audit log and SSO." }
]
export const RadioGroupCards = Html.component({
name: "RadioGroupCards",
model: Schema.Struct({ plan: Schema.NullOr(Schema.String) }),
message: RadioGroupCardsMessage
}).make({
init: () => ({ plan: "pro" }),
update: {
PickedPlan: ($, { value }) => $.evolve({ plan: value })
},
view: (h, model) =>
RadioGroup(h, {
props: { value: model.plan, items: plans.map(({ value }) => ({ value })) },
onEmit: { Picked: ({ value }) => RadioGroupCardsMessage.PickedPlan({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup, { class: "w-full max-w-sm" })
.attr("aria-label", "Plan")
.children(
plans.map(({ description, label, price, value }) =>
h.label
.class(
"flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-3.5 py-3 text-[13px] transition-colors duration-150 select-none hover:bg-accent has-[[data-checked]]:border-brand has-[[data-checked]]:bg-brand-wash"
).children(
RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value })),
h.span.class("grid flex-1 gap-0.5").children(
h.span.class("leading-4 font-medium").children(label),
h.span.class("text-muted-foreground").children(description)
),
h.span.class("leading-4 font-medium tabular-nums").children(price)
)
)
)
})
})
Horizontal
The radios in a row. Left and Right pick as Up and Down do.
Size M
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RadioGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { RadioGroupIndicator, RadioGroupLabel, RadioGroupLegend, RadioGroupRadio, RadioGroupRoot } from "#ui/radio-group"
const RadioGroupHorizontalMessage = UiSchema.TaggedEnum({ PickedSize: { value: Schema.String } })
const sizes = ["S", "M", "L", "XL"]
export const RadioGroupHorizontal = Html.component({
name: "RadioGroupHorizontal",
model: Schema.Struct({ size: Schema.NullOr(Schema.String) }),
message: RadioGroupHorizontalMessage
}).make({
init: () => ({ size: "M" }),
update: {
PickedSize: ($, { value }) => $.evolve({ size: value })
},
view: (h, model) =>
h.div.class("flex flex-col items-start gap-3.5").children(
RadioGroupLegend(h).attr("id", "radio-group-size").children("Size"),
// Left and Right move and pick, as Up and Down do, whatever the layout.
RadioGroup(h, {
props: { value: model.size, items: sizes.map((value) => ({ value })) },
onEmit: { Picked: ({ value }) => RadioGroupHorizontalMessage.PickedSize({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup, { orientation: "horizontal" })
.attr("aria-labelledby", "radio-group-size")
.children(
sizes.map((value) =>
RadioGroupLabel(h).children(
RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value })),
value
)
)
)
}),
h.p.class("text-xs text-muted-foreground tabular-nums").children(`Size ${model.size ?? "not picked"}`)
)
})
Disabled
One disabled option that the arrow keys skip, and a group that is disabled as a whole.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RadioGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { RadioGroupIndicator, RadioGroupLabel, RadioGroupRadio, RadioGroupRoot } from "#ui/radio-group"
const RadioGroupDisabledMessage = UiSchema.TaggedEnum({
PickedShipping: { value: Schema.String },
PickedRegion: { value: Schema.String }
})
const shipping = [
{ value: "standard", label: "Standard, 3 to 5 days" },
{ value: "express", label: "Express, next day" },
{ value: "pickup", label: "Store pickup (unavailable)", disabled: true }
]
const regions = ["Europe", "North America"]
export const RadioGroupDisabled = Html.component({
name: "RadioGroupDisabled",
model: Schema.Struct({ shipping: Schema.NullOr(Schema.String), region: Schema.NullOr(Schema.String) }),
message: RadioGroupDisabledMessage
}).make({
init: () => ({ shipping: "standard", region: "Europe" }),
update: {
PickedShipping: ($, { value }) => $.evolve({ shipping: value }),
PickedRegion: ($, { value }) => $.evolve({ region: value })
},
view: (h, model) =>
h.div.class("grid grid-cols-2 items-start gap-12").children(
// The arrow keys skip a disabled radio.
RadioGroup(h, {
key: "shipping",
props: {
value: model.shipping,
items: shipping.map(({ disabled, value }) => ({ value, disabled }))
},
onEmit: { Picked: ({ value }) => RadioGroupDisabledMessage.PickedShipping({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup).attr("aria-label", "Shipping").children(
shipping.map(({ label, value }) =>
RadioGroupLabel(h).children(
RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value })),
label
)
)
)
}),
RadioGroup(h, {
key: "region",
props: { value: model.region, items: regions.map((value) => ({ value })), disabled: true },
onEmit: { Picked: ({ value }) => RadioGroupDisabledMessage.PickedRegion({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup).attr("aria-label", "Region, disabled").children(
regions.map((value) =>
RadioGroupLabel(h).children(
RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value })),
value
)
)
)
})
)
})
In a form
The root holds the hidden input, and is marked invalid when nothing was picked.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RadioGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { RadioGroupIndicator, RadioGroupLabel, RadioGroupLegend, RadioGroupRadio, RadioGroupRoot } from "#ui/radio-group"
import { Button } from "#ui/button"
const RadioGroupFormMessage = UiSchema.TaggedEnum({
PickedContact: { value: Schema.String },
SubmittedForm: { contact: Schema.NullOr(Schema.String) }
})
const contacts = [
{ value: "email", label: "Email" },
{ value: "phone", label: "Phone" },
{ value: "post", label: "Post" }
]
export const RadioGroupForm = Html.component({
name: "RadioGroupForm",
model: Schema.Struct({
contact: Schema.NullOr(Schema.String),
tried: Schema.Boolean,
saved: Schema.NullOr(Schema.String)
}),
message: RadioGroupFormMessage
}).make({
init: () => ({ contact: null, tried: false, saved: null }),
update: {
PickedContact: ($, { value }) => $.evolve({ contact: value }),
SubmittedForm: ($, { contact }) => $.evolve({ tried: true, saved: contact })
},
view: (h, model) => {
const invalid = model.tried && model.contact === null
return h.form
.class("flex flex-col items-start gap-3.5")
// The root holds a hidden input once a radio is picked. Until then the form has no "contact" field.
.on("submit", ({ fields }) => RadioGroupFormMessage.SubmittedForm({ contact: fields.contact ?? null }))
.children(
RadioGroup(h, {
props: {
value: model.contact,
items: contacts.map(({ value }) => ({ value })),
name: "contact",
required: true,
invalid
},
onEmit: { Picked: ({ value }) => RadioGroupFormMessage.PickedContact({ value }) },
view: (radioGroup) =>
RadioGroupRoot(h, radioGroup)
.attrs({
"aria-labelledby": "radio-group-contact",
"aria-describedby": invalid ? "radio-group-contact-error" : undefined
})
.children(
RadioGroupLegend(h).attr("id", "radio-group-contact").children(
"How should we reach you?"
),
contacts.map(({ label, value }) =>
RadioGroupLabel(h).children(
RadioGroupRadio(h, radioGroup, { value }).children(RadioGroupIndicator(h, radioGroup, { value })),
label
)
),
invalid
? h.p.class("text-xs text-destructive").attr("id", "radio-group-contact-error").children(
"Pick one to continue."
)
: undefined
)
}),
Button(h, { size: "sm", props: { type: "submit" } }).children("Save"),
h.p.class("text-xs text-muted-foreground tabular-nums").children(
model.saved === null ? "Nothing saved yet" : `Saved contact=${model.saved}`
)
)
}
})
Anatomy
The parts the view closure receives. Apply each one to an element of your own.
| Part | Description |
|---|---|
root | The <div role="radiogroup">. It appends the hidden input once a radio is picked and name is set. |
radio | radio({ element: h.button, value }): one <button role="radio"> per entry in items. |
indicator | indicator({ element: h.span, value, keepMounted? }): undefined while its radio is unchecked and not leaving. |
value, disabled, readOnly, required, invalid | The group's state, for markup that depends on it. |
API reference
Props
| Prop | Type | Description |
|---|---|---|
value | string | null | The picked radio's value, or null when none is. Required. |
items | ReadonlyArray<{ value: string; disabled?: boolean; readOnly?: boolean }> | The radios in navigation order. Required. |
disabled | boolean | Disables every radio and submits nothing. |
readOnly | boolean | Keeps the radios focusable and navigable, but nothing is picked. |
required | boolean | Sets aria-required on the root and data-required on every part. |
invalid | boolean | Sets aria-invalid on the root. |
name | string | The hidden input's name. It is submitted when an enabled radio is picked. |
form | string | The id of the form the hidden input belongs to, when it sits outside it. |
Events
| Event | Description |
|---|---|
Picked | { value }: the radio the user chose. Store it and pass it back as value. |
Data attributes
| Attribute | Description |
|---|---|
data-checked / data-unchecked | On each radio and indicator. |
data-disabled | On the root, and on each disabled radio and its indicator. |
data-readonly | On the root, and on each read-only radio and its indicator. |
data-required | On every part of a required group. |
data-starting-style | On an indicator for the first frame after its radio is picked. |
data-ending-style | On an indicator while it stays mounted to animate out. |
Related components
The components this page's file and examples import.
- Button: A native button that can stay focusable while disabled.