# Radio Group

A set of radio buttons where no more than one can be checked at a time.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { HStack } from "@/components/ui/stack"

const styles = stylex.create({
  group: { width: "fit-content" },
})

export default function RadioGroupDemo() {
  return (
    <RadioGroup defaultValue="kelvin" xstyle={styles.group}>
      <HStack gap={3} align="center">
        <RadioGroupItem value="celsius" id="scale-celsius" />
        <Label htmlFor="scale-celsius">Celsius</Label>
      </HStack>
      <HStack gap={3} align="center">
        <RadioGroupItem value="kelvin" id="scale-kelvin" />
        <Label htmlFor="scale-kelvin">Kelvin</Label>
      </HStack>
      <HStack gap={3} align="center">
        <RadioGroupItem value="fahrenheit" id="scale-fahrenheit" />
        <Label htmlFor="scale-fahrenheit">Fahrenheit</Label>
      </HStack>
    </RadioGroup>
  )
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/radio-group
```

Needs the [arene setup](https://www.arene.style/docs/installation) first.

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex clsx
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `states.ts` and
   `state-styles.ts` from the same page. The radio group imports both. The examples caption
   their buttons with a [Label](https://www.arene.style/docs/components/label) or a
   [Field](https://www.arene.style/docs/components/field).

   Paste `field-state.ts` from the same installation page.

3. Paste this source into the file named in its title.

   ```tsx title="components/ui/radio-group.tsx"
   "use client"

   import { use, type CSSProperties } from "react"
   import { Radio as RadioPrimitive } from "@base-ui/react/radio"
   import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"

   import { stateStyles } from "@/lib/state-styles"
   import { FieldStateContext } from "@/lib/field-state"
   import { states } from "@/theme/states"
   import { color, duration, ease, radius, space } from "@/theme/tokens.stylex"

   const styles = stylex.create({
     group: {
       display: "grid",
       gap: space.s2,
       width: "100%",
     },
     item: {
       position: "relative",
       display: "flex",
       alignItems: "center",
       justifyContent: "center",
       flexShrink: 0,
       width: space.s4,
       height: space.s4,
       borderRadius: radius.full,
       borderWidth: 1,
       borderStyle: "solid",
       transitionProperty: "color, background-color, border-color, box-shadow",
       transitionDuration: duration.color,
       transitionTimingFunction: ease.standard,
       "::after": {
         content: '""',
         position: "absolute",
         insetInline: `calc(-1 * ${space.s3})`,
         insetBlock: `calc(-1 * ${space.s2})`,
       },
     },
     indicator: {
       width: space.s1_5,
       height: space.s1_5,
       borderRadius: radius.full,
       backgroundColor: color.current,
       transitionProperty: "opacity, transform",
       transitionDuration: {
         default: duration.color,
         "@media (prefers-reduced-motion: reduce)": "0s",
       },
       transitionTimingFunction: ease.standard,
     },
     indicatorHidden: { opacity: 0, transform: "scale(0.6)" },
   })

   const radioGroupStyles = {
     group: styles.group,
     item: styles.item,
     indicator: styles.indicator,
     indicatorHidden: styles.indicatorHidden,
     choice: states.choice,
     checked: states.choiceChecked,
     disabled: states.disabled,
     invalid: states.invalidRing,
   }

   type StyleProps = {
     xstyle?: StyleXStyles
     className?: string
   }

   type StateOverrides = StyleProps & { style?: CSSProperties }

   type RadioGroupProps = Omit<RadioGroupPrimitive.Props, "className"> & StyleProps

   function RadioGroup({ xstyle, className, ...props }: RadioGroupProps) {
     const sx = stylex.props(styles.group, xstyle)

     return (
       <RadioGroupPrimitive
         data-slot="radio-group"
         {...sx}
         {...props}
         className={clsx(sx.className, className)}
       />
     )
   }

   type RadioGroupItemProps = Omit<RadioPrimitive.Root.Props, "className" | "style"> & StateOverrides

   function RadioGroupItem({ xstyle, style, className, ...props }: RadioGroupItemProps) {
     const fieldState = use(FieldStateContext)
     return (
       <RadioPrimitive.Root
         data-slot="radio-group-item"
         {...props}
         {...stateStyles(
           (state) => [
             styles.item,
             states.choice,
             states.focusRing,
             (state.valid === false ||
               fieldState?.valid === false ||
               props["aria-invalid"] === true ||
               props["aria-invalid"] === "true") &&
               states.invalidRing,
             state.checked && states.choiceChecked,
             state.disabled && states.disabled,
             xstyle,
           ],
           { className, style },
         )}
       >
         <RadioPrimitive.Indicator
           data-slot="radio-group-indicator"
           {...stateStyles((state) => [
             styles.indicator,
             (state.transitionStatus === "starting" || state.transitionStatus === "ending") &&
               styles.indicatorHidden,
           ])}
         />
       </RadioPrimitive.Root>
     )
   }

   export { RadioGroup, RadioGroupItem, radioGroupStyles }
   ```

4. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
```

```tsx
<RadioGroup defaultValue="kelvin">
  <HStack gap={3} align="center">
    <RadioGroupItem value="kelvin" id="r1" />
    <Label htmlFor="r1">Kelvin</Label>
  </HStack>
</RadioGroup>
```

`RadioGroup` is a grid that fills its container and stacks its children. Match
each label's `htmlFor` to its button's `id`, or wrap the button in the label.

```text
RadioGroup
├── RadioGroupItem
└── RadioGroupItem
```

## Selected value

Use `defaultValue` for an uncontrolled group, or `value` and `onValueChange` to
control it. `value` is the `value` of the selected `RadioGroupItem`, which can
be any type.

```tsx
const [scale, setScale] = useState("kelvin")

return (
  <RadioGroup value={scale} onValueChange={setScale}>
    …
  </RadioGroup>
)
```

## Description

Put a `Field` around each button and a `FieldContent` beside it to add a line
of helper text under the label.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Field, FieldContent, FieldDescription, FieldLabel } from "@/components/ui/field"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  group: { maxWidth: width.sm },
})

const scales = [
  { id: "celsius", title: "Celsius", description: "Water freezes at 0 and boils at 100." },
  { id: "kelvin", title: "Kelvin", description: "Starts at absolute zero, so never negative." },
  { id: "fahrenheit", title: "Fahrenheit", description: "Water freezes at 32 and boils at 212." },
]

export default function RadioGroupDescription() {
  return (
    <RadioGroup defaultValue="kelvin" xstyle={styles.group}>
      {scales.map((scale) => (
        <Field key={scale.id} orientation="horizontal">
          <RadioGroupItem value={scale.id} id={`desc-${scale.id}`} />
          <FieldContent>
            <FieldLabel>{scale.title}</FieldLabel>
            <FieldDescription>{scale.description}</FieldDescription>
          </FieldContent>
        </Field>
      ))}
    </RadioGroup>
  )
}
```

## Choice card

Wrap a whole `Field` in a `FieldLabel` to turn the option into a card, and pass
`checked` to mark the selected one.

```tsx
"use client"

import { useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Field, FieldContent, FieldDescription, FieldLabel, FieldTitle } from "@/components/ui/field"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  group: { maxWidth: width.sm },
})

const plans = [
  { id: "student", title: "Student", description: "For one person and one notebook." },
  { id: "lab", title: "Lab", description: "For a research group of up to ten." },
  { id: "institute", title: "Institute", description: "For departments with many groups." },
]

export default function RadioGroupChoiceCard() {
  const [plan, setPlan] = useState("student")

  return (
    <RadioGroup value={plan} onValueChange={setPlan} xstyle={styles.group}>
      {plans.map((entry) => (
        <FieldLabel key={entry.id} htmlFor={`plan-${entry.id}`} checked={plan === entry.id}>
          <Field orientation="horizontal">
            <FieldContent>
              <FieldTitle>{entry.title}</FieldTitle>
              <FieldDescription>{entry.description}</FieldDescription>
            </FieldContent>
            <RadioGroupItem value={entry.id} id={`plan-${entry.id}`} />
          </Field>
        </FieldLabel>
      ))}
    </RadioGroup>
  )
}
```

> **Note**
>
> `FieldLabel` cannot read the button's state, so `checked` is a prop you set from
> the same value you give `RadioGroup`. That makes the card a controlled group.

## Fieldset

Use `Fieldset` and `FieldsetLegend` to caption the group as a whole, and give the
group a `name` to submit it with a form.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { FieldsetLegend, Fieldset } from "@/components/ui/fieldset"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { textStyles } from "@/components/ui/text"
import { width } from "@/theme/tokens.stylex"

const styles = stylex.create({
  fieldset: { maxWidth: width.xs },
})

const plans = [
  { id: "monthly", label: "Monthly ($12/month)" },
  { id: "yearly", label: "Yearly ($120/year)" },
  { id: "lifetime", label: "Lifetime ($360)" },
]

export default function RadioGroupFieldset() {
  return (
    <Fieldset xstyle={styles.fieldset}>
      <FieldsetLegend variant="label">Billing period</FieldsetLegend>
      <FieldDescription>Paying yearly costs two months less than monthly.</FieldDescription>
      <RadioGroup defaultValue="monthly" name="subscription-plan">
        {plans.map((plan) => (
          <Field key={plan.id} orientation="horizontal">
            <RadioGroupItem value={plan.id} id={`billing-${plan.id}`} />
            <FieldLabel xstyle={textStyles.weights.normal}>{plan.label}</FieldLabel>
          </Field>
        ))}
      </RadioGroup>
    </Fieldset>
  )
}
```

## Disabled

Set `disabled` on `Field` to disable its control and dim its label, or on a bare control directly.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Field, FieldLabel } from "@/components/ui/field"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { textStyles } from "@/components/ui/text"

const styles = stylex.create({
  group: { width: "fit-content" },
})

export default function RadioGroupDisabled() {
  return (
    <RadioGroup defaultValue="standard" xstyle={styles.group}>
      <Field orientation="horizontal" disabled>
        <RadioGroupItem value="free" id="shipping-free" />
        <FieldLabel xstyle={textStyles.weights.normal}>Free (unavailable)</FieldLabel>
      </Field>
      <Field orientation="horizontal">
        <RadioGroupItem value="standard" id="shipping-standard" />
        <FieldLabel xstyle={textStyles.weights.normal}>Standard</FieldLabel>
      </Field>
      <Field orientation="horizontal">
        <RadioGroupItem value="express" id="shipping-express" />
        <FieldLabel xstyle={textStyles.weights.normal}>Express</FieldLabel>
      </Field>
    </RadioGroup>
  )
}
```

## Invalid

Set `invalid` on `Field` to style its control, or `aria-invalid` on a bare control. The examples show both.

```tsx
import { Field, FieldLabel, FieldError } from "@/components/ui/field"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { HStack, VStack } from "@/components/ui/stack"
const channels = [
  { id: "email", label: "Email" },
  { id: "sms", label: "Text message" },
  { id: "both", label: "Email and text" },
]
function Options({ bare = false }: { bare?: boolean }) {
  return (
    <RadioGroup aria-label={bare ? "Run alerts" : undefined}>
      {channels.map((channel) => (
        <HStack key={channel.id} gap={2} align="center">
          <RadioGroupItem
            value={channel.id}
            id={`${bare ? "bare" : "field"}-notify-${channel.id}`}
            aria-invalid={bare || undefined}
          />
          <Label htmlFor={`${bare ? "bare" : "field"}-notify-${channel.id}`}>{channel.label}</Label>
        </HStack>
      ))}
    </RadioGroup>
  )
}
export default function RadioGroupInvalid() {
  return (
    <VStack gap={5}>
      <Options bare />
      <Field invalid>
        <FieldLabel>Run alerts</FieldLabel>
        <Options />
        <FieldError>Choose where run alerts should go.</FieldError>
      </Field>
    </VStack>
  )
}
```

## API reference

Pass `render` to replace a part's element or compose it with another component.

Both parts wrap the Base UI `RadioGroup` and `Radio` primitives and accept
their props. See the [Base UI reference](https://base-ui.com/react/components/radio-group).
Each part also takes `xstyle` and `className`.

### RadioGroup

| Prop            | Type                              | Default |
| --------------- | --------------------------------- | ------- |
| `value`         | `Value`                           | —       |
| `defaultValue`  | `Value`                           | —       |
| `onValueChange` | `(value: Value, details) => void` | —       |
| `name`          | `string`                          | —       |
| `disabled`      | `boolean`                         | `false` |
| `readOnly`      | `boolean`                         | `false` |
| `required`      | `boolean`                         | `false` |
| `form`          | `string`                          | —       |
| `xstyle`        | `StyleXStyles`                    | —       |
| `className`     | `string`                          | —       |

The root is a `<div role="radiogroup">`. Arrow keys move between the buttons
and select as they go, and the group is one tab stop.

### RadioGroupItem

| Prop           | Type                    | Default |
| -------------- | ----------------------- | ------- |
| `value`        | `Value`                 | —       |
| `disabled`     | `boolean`               | `false` |
| `readOnly`     | `boolean`               | `false` |
| `required`     | `boolean`               | `false` |
| `aria-invalid` | `boolean`               | —       |
| `id`           | `string`                | —       |
| `inputRef`     | `Ref<HTMLInputElement>` | —       |
| `xstyle`       | `StyleXStyles`          | —       |
| `style`        | `CSSProperties`         | —       |
| `className`    | `string`                | —       |

The item is a `<span role="radio">`. Base UI renders a hidden `<input>` beside
it that carries `id`, `name` and `value`. A label's `htmlFor` and a form
submission reach the item through that input.

### radioGroupStyles

The style maps behind the component. Spread them onto any element.

| Key               | What it is                                    |
| ----------------- | --------------------------------------------- |
| `group`           | The grid and its gap                          |
| `item`            | The circle: size, border width, hit area      |
| `indicator`       | The dot and its fade                          |
| `indicatorHidden` | The dot faded out and scaled down             |
| `choice`          | The hairline edge and fill at a choice's size |
| `checked`         | The flat primary fill and inverted dot colour |
| `disabled`        | The dimmed, non-interactive state             |
| `invalid`         | The destructive border and ring               |

`item` has no colour and no focus ring. Everything else comes from `states`
in `theme/states.ts`, the same material the checkbox uses. Merge `choice`, then
`states.focusRing`. Merge `invalid` before `checked`, so a selected invalid
button keeps the primary fill and shows only the destructive ring.

### Data attributes

| Attribute                                         | On         | Effect                                             |
| ------------------------------------------------- | ---------- | -------------------------------------------------- |
| `data-slot="radio-group"`                         | the root   | Targets the grid from a parent                     |
| `data-slot="radio-group-item"`                    | a button   | Targets the circle                                 |
| `data-slot="radio-group-indicator"`               | the dot    | Targets the animated indicator                     |
| `data-checked`, `data-unchecked`                  | item, dot  | Base UI writes them                                |
| `data-disabled`, `data-readonly`, `data-required` | root, item | Base UI writes them                                |
| `data-starting-style`, `data-ending-style`        | the dot    | Base UI writes them while the dot enters or leaves |
