Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. 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
      ))
    
  3. Import it

    import { RadioGroupRoot, RadioGroupRadio, RadioGroupIndicator, RadioGroupLegend, RadioGroupLabel } from "#ui/radio-group"
    

Usage

Basic.ts
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.

Notify me about

Every comment, mention and status change.

Only when someone mentions you by name.

You can still see activity in the inbox.

Cards

Each card is the label, filled while the radio inside it is picked.

Horizontal

The radios in a row. Left and Right pick as Up and Down do.

Size

Size M

Disabled

One disabled option that the arrow keys skip, and a group that is disabled as a whole.

In a form

The root holds the hidden input, and is marked invalid when nothing was picked.

How should we reach you?

Nothing saved yet

Anatomy

The parts the view closure receives. Apply each one to an element of your own.

PartDescription
rootThe <div role="radiogroup">. It appends the hidden input once a radio is picked and name is set.
radioradio({ element: h.button, value }): one <button role="radio"> per entry in items.
indicatorindicator({ element: h.span, value, keepMounted? }): undefined while its radio is unchecked and not leaving.
value, disabled, readOnly, required, invalidThe group's state, for markup that depends on it.

API reference

Props

PropTypeDescription
valuestring | nullThe picked radio's value, or null when none is. Required.
itemsReadonlyArray<{ value: string; disabled?: boolean; readOnly?: boolean }>The radios in navigation order. Required.
disabledbooleanDisables every radio and submits nothing.
readOnlybooleanKeeps the radios focusable and navigable, but nothing is picked.
requiredbooleanSets aria-required on the root and data-required on every part.
invalidbooleanSets aria-invalid on the root.
namestringThe hidden input's name. It is submitted when an enabled radio is picked.
formstringThe id of the form the hidden input belongs to, when it sits outside it.

Events

EventDescription
Picked{ value }: the radio the user chose. Store it and pass it back as value.

Data attributes

AttributeDescription
data-checked / data-uncheckedOn each radio and indicator.
data-disabledOn the root, and on each disabled radio and its indicator.
data-readonlyOn the root, and on each read-only radio and its indicator.
data-requiredOn every part of a required group.
data-starting-styleOn an indicator for the first frame after its radio is picked.
data-ending-styleOn an indicator while it stays mounted to animate out.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.