# Radio

A set of options where only one can be selected.

Source: [radio.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/radio.tsx)

```tsx
import { FieldItem, FieldLabel, FieldLegend, FieldSet } from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";

export default function RadioBasic() {
  return (
    <FieldSet>
      <FieldLegend>Density</FieldLegend>
      <RadioGroup defaultValue="comfortable">
        <FieldItem>
          <Radio value="compact" />
          <FieldLabel>Compact</FieldLabel>
        </FieldItem>
        <FieldItem>
          <Radio value="comfortable" />
          <FieldLabel>Comfortable</FieldLabel>
        </FieldItem>
        <FieldItem>
          <Radio value="spacious" />
          <FieldLabel>Spacious</FieldLabel>
        </FieldItem>
      </RadioGroup>
    </FieldSet>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/radio
```

## Usage

Pair each `Radio` with a label in a `FieldItem`, and label the group with a `FieldSet` and a
`FieldLegend`, from [Field](https://ui.jarv.is/components/field.md).

```tsx
import { FieldItem, FieldLabel, FieldLegend, FieldSet } from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";

export function ThemePicker() {
  return (
    <FieldSet>
      <FieldLegend>Theme</FieldLegend>
      <RadioGroup defaultValue="system">
        <FieldItem>
          <Radio value="light" />
          <FieldLabel>Light</FieldLabel>
        </FieldItem>
        <FieldItem>
          <Radio value="dark" />
          <FieldLabel>Dark</FieldLabel>
        </FieldItem>
        <FieldItem>
          <Radio value="system" />
          <FieldLabel>System</FieldLabel>
        </FieldItem>
      </RadioGroup>
    </FieldSet>
  );
}
```

Without a visible legend, give the `RadioGroup` an `aria-label` instead.

## Composition

- `RadioGroup`
  - [`FieldItem`](https://ui.jarv.is/components/field.md)
    - `Radio`
    - [`FieldLabel`](https://ui.jarv.is/components/field.md)

## Examples

### With descriptions

Wrap the label in a `FieldContent` with a `FieldDescription` when an option needs explaining.

```tsx
import {
  FieldContent,
  FieldDescription,
  FieldItem,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";

export default function RadioWithDescriptions() {
  return (
    <FieldSet className="w-full max-w-sm">
      <FieldLegend>Visibility</FieldLegend>
      <RadioGroup defaultValue="private">
        <FieldItem>
          <Radio value="public" />
          <FieldContent>
            <FieldLabel>Public</FieldLabel>
            <FieldDescription>Anyone with the link can view it.</FieldDescription>
          </FieldContent>
        </FieldItem>
        <FieldItem>
          <Radio value="private" />
          <FieldContent>
            <FieldLabel>Private</FieldLabel>
            <FieldDescription>Only people you invite can view it.</FieldDescription>
          </FieldContent>
        </FieldItem>
      </RadioGroup>
    </FieldSet>
  );
}
```

### Disabled

Set `disabled` on a `Radio`, or on the `RadioGroup` to disable all of them.

```tsx
import {
  FieldContent,
  FieldDescription,
  FieldItem,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";

export default function RadioDisabled() {
  return (
    <FieldSet>
      <FieldLegend>Layout</FieldLegend>
      <RadioGroup defaultValue="list">
        <FieldItem>
          <Radio value="list" />
          <FieldLabel>List</FieldLabel>
        </FieldItem>
        <FieldItem>
          <Radio value="board" />
          <FieldLabel>Board</FieldLabel>
        </FieldItem>
        <FieldItem disabled>
          <Radio value="timeline" />
          <FieldContent>
            <FieldLabel>Timeline</FieldLabel>
            <FieldDescription>Not available on small screens.</FieldDescription>
          </FieldContent>
        </FieldItem>
      </RadioGroup>
    </FieldSet>
  );
}
```

### Read-only

Set `readOnly` on the `RadioGroup` to show the selected option without letting anyone change it.
The radios stay focusable, and the value still submits with a form.

```tsx
import { FieldItem, FieldLabel, FieldLegend, FieldSet } from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";

export default function RadioReadOnly() {
  return (
    <FieldSet>
      <FieldLegend>Data region</FieldLegend>
      <RadioGroup readOnly defaultValue="eu">
        <FieldItem>
          <Radio value="us" />
          <FieldLabel>United States</FieldLabel>
        </FieldItem>
        <FieldItem>
          <Radio value="eu" />
          <FieldLabel>European Union</FieldLabel>
        </FieldItem>
      </RadioGroup>
    </FieldSet>
  );
}
```

### Choice cards

Set `variant="card"` on each `FieldItem` to frame it as a card. Its `FieldLabel` makes the whole
card clickable.

```tsx
import {
  FieldContent,
  FieldDescription,
  FieldItem,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";

const plans = [
  { value: "starter", name: "Starter", description: "Up to 3 projects and 5 members." },
  { value: "team", name: "Team", description: "Unlimited projects and 25 members." },
  { value: "enterprise", name: "Enterprise", description: "SSO, audit logs and priority support." },
];

export default function RadioChoiceCards() {
  return (
    <FieldSet className="w-full max-w-sm">
      <FieldLegend>Plan</FieldLegend>
      <RadioGroup defaultValue="team">
        {plans.map((plan) => (
          <FieldItem key={plan.value} variant="card">
            <FieldContent>
              <FieldLabel>{plan.name}</FieldLabel>
              <FieldDescription>{plan.description}</FieldDescription>
            </FieldContent>
            <Radio value={plan.value} />
          </FieldItem>
        ))}
      </RadioGroup>
    </FieldSet>
  );
}
```

### Invalid

Wrap the group in a [`Field`](https://ui.jarv.is/components/field.md), set `invalid` on it, and explain the problem
with a `FieldError`.

```tsx
import {
  Field,
  FieldError,
  FieldItem,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";

export default function RadioInvalid() {
  return (
    <Field invalid className="w-fit">
      <FieldSet>
        <FieldLegend>Shipping speed</FieldLegend>
        <RadioGroup>
          <FieldItem>
            <Radio value="standard" />
            <FieldLabel>Standard</FieldLabel>
          </FieldItem>
          <FieldItem>
            <Radio value="express" />
            <FieldLabel>Express</FieldLabel>
          </FieldItem>
        </RadioGroup>
      </FieldSet>
      <FieldError>Choose a shipping speed.</FieldError>
    </Field>
  );
}
```

### In a form

Wrap the group in a `Field` with a `name`, and the form submits the selected radio's `value` under
it. Leave out `defaultValue` so that someone has to choose, and with `required` on the
`RadioGroup`, the form won't submit until they do, failing validation with `valueMissing`.

```tsx
"use client";

import { Button } from "@/components/ui/button";
import {
  Field,
  FieldError,
  FieldItem,
  FieldLabel,
  FieldLegend,
  FieldSet,
  Form,
} from "@/components/ui/field";
import { Radio, RadioGroup } from "@/components/ui/radio";
import { toast } from "@/components/ui/toast";

export default function RadioForm() {
  return (
    <Form
      className="max-w-sm"
      onSubmit={(event) => {
        event.preventDefault();
        const entries = Array.from(new FormData(event.currentTarget), ([name, value]) =>
          typeof value === "string" ? `${name}=${value}` : name,
        );
        toast.add({ title: "Form submitted", description: entries.join(", ") });
      }}
    >
      <Field name="plan">
        <FieldSet>
          <FieldLegend>Plan</FieldLegend>
          <RadioGroup required>
            <FieldItem>
              <Radio value="hobby" />
              <FieldLabel>Hobby</FieldLabel>
            </FieldItem>
            <FieldItem>
              <Radio value="pro" />
              <FieldLabel>Pro</FieldLabel>
            </FieldItem>
            <FieldItem>
              <Radio value="enterprise" />
              <FieldLabel>Enterprise</FieldLabel>
            </FieldItem>
          </RadioGroup>
        </FieldSet>
        <FieldError match="valueMissing">Choose a plan.</FieldError>
      </Field>
      <Button type="submit" variant="primary" className="self-start">
        Continue
      </Button>
    </Form>
  );
}
```

## Props

`radioVariants()` returns the classes that draw the circle. Use them to show a selected state on an
element that isn't a control of its own.

| Part | Extends |
| --- | --- |
| `Radio` | [`Radio.Root`](https://base-ui.com/react/components/radio#root) |
| `RadioGroup` | [`RadioGroup`](https://base-ui.com/react/components/radio-group#api-reference) |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### Radio

| Prop            | Type                                                                                   | Default | Description                                                                                                                                                                               |
| --------------- | -------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `value`         | `any`                                                                                  | —       | The unique identifying value of the radio in a group.                                                                                                                                     |
| `disabled?`     | `boolean`                                                                              | —       | Whether the component should ignore user interaction.                                                                                                                                     |
| `required?`     | `boolean`                                                                              | —       | Whether the user must choose a value before submitting a form.                                                                                                                            |
| `readOnly?`     | `boolean`                                                                              | —       | Whether the user should be unable to select the radio button.                                                                                                                             |
| `inputRef?`     | `React.Ref<HTMLInputElement>`                                                          | —       | A ref to access the hidden input element.                                                                                                                                                 |
| `nativeButton?` | `boolean`                                                                              | `false` | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `true` if the rendered element is a native button.                              |
| `className?`    | `string \| ((state: RadioRootState) => string \| undefined)`                           | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`        | `React.CSSProperties \| ((state: RadioRootState) => React.CSSProperties \| undefined)` | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`       | `ComponentRenderFn<HTMLProps, RadioRootState> \| React.ReactElement`                   | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### RadioGroup

| Prop             | Type                                                                                    | Default | Description                                                                                                                                                                               |
| ---------------- | --------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `disabled?`      | `boolean`                                                                               | `false` | Whether the component should ignore user interaction.                                                                                                                                     |
| `readOnly?`      | `boolean`                                                                               | `false` | Whether the user should be unable to select a different radio button in the group.                                                                                                        |
| `required?`      | `boolean`                                                                               | `false` | Whether the user must choose a value before submitting a form.                                                                                                                            |
| `name?`          | `string`                                                                                | —       | Identifies the field when a form is submitted.                                                                                                                                            |
| `form?`          | `string`                                                                                | —       | Identifies the form that owns the radio inputs. Useful when the radio group is rendered outside the form.                                                                                 |
| `value?`         | `any`                                                                                   | —       | The controlled value of the radio item that should be currently selected. To render an uncontrolled radio group, use the `defaultValue` prop instead.                                     |
| `defaultValue?`  | `any`                                                                                   | —       | The uncontrolled value of the radio button that should be initially selected. To render a controlled radio group, use the `value` prop instead.                                           |
| `onValueChange?` | `((value: any, eventDetails: RadioGroup.ChangeEventDetails) => void)`                   | —       | Callback fired when the value changes.                                                                                                                                                    |
| `inputRef?`      | `React.Ref<HTMLInputElement>`                                                           | —       | A ref to access the hidden input element.                                                                                                                                                 |
| `className?`     | `string \| ((state: RadioGroupState) => string \| undefined)`                           | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`         | `React.CSSProperties \| ((state: RadioGroupState) => React.CSSProperties \| undefined)` | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`        | `ComponentRenderFn<HTMLProps, RadioGroupState> \| React.ReactElement`                   | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |
