# Radio

## Introduction

The Radio component provides a single-selection interface where users can choose exactly one option from a set of mutually exclusive choices. When one radio button is selected, any previously selected option in the same group is automatically deselected.

Radio buttons are built on Joy UI's Radio and RadioGroup components, supporting multiple visual variants, sizes, colors, and advanced customization such as custom icons, overlay interactions, and icon-free designs. They are ideal for settings forms, preference panels, and any UI where a user must commit to a single option from a predefined list.

```tsx
<Radio />
```

| Field         | Description | Default |
| ------------- | ----------- | ------- |
| checked       | —           | —       |
| color         | —           | —       |
| checkedIcon   | —           | —       |
| disabled      | —           | —       |
| disableIcon   | —           | —       |
| label         | —           | —       |
| name          | —           | —       |
| onChange      | —           | —       |
| overlay       | —           | —       |
| readOnly      | —           | —       |
| required      | —           | —       |
| size          | —           | —       |
| uncheckedIcon | —           | —       |
| variant       | —           | —       |

## Usage

```tsx
import { Radio, RadioGroup } from '@ceed/cds';

function MyComponent() {
  const [selectedValue, setSelectedValue] = useState('option1');

  return (
    <RadioGroup name="example" value={selectedValue} onChange={(e) => setSelectedValue(e.target.value)}>
      <Radio value="option1" label="Option 1" />
      <Radio value="option2" label="Option 2" />
      <Radio value="option3" label="Option 3" />
    </RadioGroup>
  );
}
```

## Variants

Radio supports four visual variants: `outlined` (default), `soft`, `solid`, and `plain`. Choose a variant that fits the visual context of your form.

```tsx
<FormControl>
    <FormLabel>Variants</FormLabel>
    <RadioGroup defaultValue="outlined" name="radio-buttons-group">
      <Radio value="outlined" label="Outlined" variant="outlined" />
      <Radio value="soft" label="Soft" variant="soft" />
      <Radio value="solid" label="Solid" variant="solid" />
      <Radio value="plain" label="Plain" variant="plain" />
    </RadioGroup>
  </FormControl>
```

## Sizes

Three size presets are available: `sm`, `md` (default), and `lg`. Use smaller sizes for compact layouts and larger sizes for touch-friendly interfaces.

```tsx
<FormControl>
    <FormLabel>Sizes</FormLabel>
    <RadioGroup defaultValue="medium" name="radio-buttons-group">
      <Radio value="small" label="Small" size="sm" />
      <Radio value="medium" label="Medium" size="md" />
      <Radio value="large" label="Large" size="lg" />
    </RadioGroup>
  </FormControl>
```

## Colors

Radio supports five semantic colors: `primary`, `neutral`, `danger`, `success`, and `warning`. Use semantic colors to convey meaning -- for example, `danger` for destructive options or `success` for confirmed selections.

```tsx
<FormControl>
    <FormLabel>Colors</FormLabel>
    <RadioGroup defaultValue="medium" name="radio-buttons-group">
      <Radio value="primary" label="Primary" color="primary" />
      <Radio value="neutral" label="Neutral" color="neutral" />
      <Radio value="danger" label="Danger" color="danger" />
      <Radio value="success" label="Success" color="success" />
      <Radio value="warning" label="Warning" color="warning" />
    </RadioGroup>
  </FormControl>
```

## Custom Icons

Replace the default radio indicator with custom icons using the `checkedIcon` prop. This is useful for card-style selectors where the selection state needs a distinctive visual treatment.

```tsx
<RadioGroup
    aria-label="platform"
    defaultValue="Website"
    overlay
    name="platform"
    sx={{
      flexDirection: "row",
      gap: 2,
      [`& .${radioClasses.checked}`]: {
        [`& .${radioClasses.action}`]: {
          inset: -1,
          border: "3px solid",
          borderColor: "primary.500"
        }
      },
      [`& .${radioClasses.radio}`]: {
        display: "contents",
        "& > svg": {
          zIndex: 2,
          position: "absolute",
          top: "-8px",
          right: "-8px",
          bgcolor: "background.surface",
          borderRadius: "50%"
        }
      }
    }}
  >
    {["Website", "Documents", "Social Account"].map((value) => (
      <Sheet
        key={value}
        variant="outlined"
        sx={{
          borderRadius: "md",
          boxShadow: "sm",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 1.5,
          p: 2,
          minWidth: 120
        }}
      >
        <Radio id={value} value={value} checkedIcon={<CheckCircleRoundedIcon />} />
        <Avatar variant="soft" size="sm" />
        <FormLabel htmlFor={value}>{value}</FormLabel>
      </Sheet>
    ))}
  </RadioGroup>
```

## No Icon

Use the `disableIcon` prop to hide the radio indicator entirely. This pattern is commonly used for card-style selectors where the entire card acts as the selectable target, and the selection state is conveyed through border or background styling.

```tsx
<Box
    sx={{
      width: 300
    }}
  >
    <FormLabel
      id="storage-label"
      sx={{
        mb: 2,
        fontWeight: "xl",
        fontSize: "xs",
        letterSpacing: "0.15rem"
      }}
    >
      Storage
    </FormLabel>
    <RadioGroup
      aria-labelledby="storage-label"
      defaultValue="512GB"
      size="lg"
      sx={{
        gap: 1.5
      }}
    >
      {["512GB", "1TB", "2TB"].map((value) => (
        <Sheet
          key={value}
          sx={{
            p: 2,
            borderRadius: "md",
            boxShadow: "sm"
          }}
        >
          <Radio
            label={`${value} SSD storage`}
            overlay
            disableIcon
            value={value}
            slotProps={{
              label: ({ checked }) => ({
                sx: {
                  fontWeight: "lg",
                  fontSize: "md",
                  color: checked ? "text.primary" : "text.secondary"
                }
              }),
              action: ({ checked }) => ({
                sx: (theme) => ({
                  ...(checked && {
                    "--variant-borderWidth": "2px",
                    "&&": {
                      // && to increase the specificity to win the base :hover styles
                      borderColor: theme.vars.palette.primary[500]
                    }
                  })
                })
              })
            }}
          />
        </Sheet>
      ))}
    </RadioGroup>
  </Box>
```

## Segmented Controls

Radio buttons can be styled as segmented controls for compact, inline option switching. This pattern works well for toolbar-style controls where horizontal space is limited.

```tsx
<Box
    sx={{
      display: "flex",
      alignItems: "center",
      gap: 2
    }}
  >
    <Typography id="segmented-controls-example" fontWeight="lg" fontSize="sm">
      Justify:
    </Typography>
    <RadioGroup
      orientation="horizontal"
      aria-labelledby="segmented-controls-example"
      name="justify"
      value={justify}
      onChange={(event: React.ChangeEvent<HTMLInputElement>) => setJustify(event.target.value)}
      sx={{
        minHeight: 48,
        padding: "4px",
        borderRadius: "12px",
        bgcolor: "neutral.softBg",
        "--RadioGroup-gap": "4px",
        "--Radio-actionRadius": "8px"
      }}
    >
      {["flex-start", "center", "flex-end"].map((item) => (
        <Radio
          key={item}
          color="neutral"
          value={item}
          disableIcon
          label={item}
          variant="plain"
          sx={{
            px: 2,
            alignItems: "center"
          }}
          slotProps={{
            action: ({ checked }) => ({
              sx: {
                ...(checked && {
                  bgcolor: "background.surface",
                  boxShadow: "sm",
                  "&:hover": {
                    bgcolor: "background.surface"
                  }
                })
              }
            })
          }}
        />
      ))}
    </RadioGroup>
  </Box>
```

## Product Attributes

Radio groups can be customized to represent product attributes such as colors and sizes. Using `overlay`, `disableIcon`, and custom `Sheet` containers, you can create rich visual selectors.

```tsx
<Box
    sx={{
      overflow: "auto",
      px: 2
    }}
  >
    <FormLabel
      id="product-color-attribute"
      sx={{
        mb: 1.5,
        fontWeight: "xl",
        textTransform: "uppercase",
        fontSize: "xs",
        letterSpacing: "0.1em"
      }}
    >
      Color
    </FormLabel>
    <RadioGroup
      aria-labelledby="product-color-attribute"
      defaultValue="warning"
      sx={{
        gap: 2,
        flexWrap: "wrap",
        flexDirection: "row"
      }}
    >
      {(["primary", "neutral", "danger", "success", "warning"] as const).map((color) => (
        <Sheet
          key={color}
          sx={{
            position: "relative",
            width: 40,
            height: 40,
            flexShrink: 0,
            bgcolor: `${color}.solidBg`,
            borderRadius: "50%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center"
          }}
        >
          <Radio
            overlay
            variant="solid"
            color={color}
            checkedIcon={<Done fontSize="large" />}
            value={color}
            slotProps={{
              input: {
                "aria-label": color
              },
              radio: {
                sx: {
                  display: "contents",
                  "--variant-borderWidth": "2px"
                }
              }
            }}
            sx={{
              "--joy-focus-outlineOffset": "4px",
              "--joy-palette-focusVisible": (theme) => theme.vars.palette[color][500],
              [`& .${radioClasses.action}.${radioClasses.focusVisible}`]: {
                outlineWidth: "2px"
              }
            }}
          />
        </Sheet>
      ))}
    </RadioGroup>
    <br />
    <FormLabel
      id="product-size-attribute"
      sx={{
        mb: 1.5,
        fontWeight: "xl",
        textTransform: "uppercase",
        fontSize: "xs",
        letterSpacing: "0.1em"
      }}
    >
      Size
    </FormLabel>
    <RadioGroup
      aria-labelledby="product-size-attribute"
      defaultValue="M"
      sx={{
        gap: 2,
        mb: 2,
        flexWrap: "wrap",
        flexDirection: "row"
      }}
    >
      {["XS", "S", "M", "L", "XL"].map((size) => (
        <Sheet
          key={size}
          sx={{
            position: "relative",
            width: 40,
            height: 40,
            flexShrink: 0,
            borderRadius: "50%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            "--joy-focus-outlineOffset": "4px",
            "--joy-palette-focusVisible": (theme) => theme.vars.palette.neutral.outlinedBorder,
            [`& .${radioClasses.checked}`]: {
              [`& .${radioClasses.label}`]: {
                fontWeight: "lg"
              },
              [`& .${radioClasses.action}`]: {
                "--variant-borderWidth": "2px",
                borderColor: "text.secondary"
              }
            },
            [`& .${radioClasses.action}.${radioClasses.focusVisible}`]: {
              outlineWidth: "2px"
            }
          }}
        >
          <Radio color="neutral" overlay disableIcon value={size} label={size} />
        </Sheet>
      ))}
    </RadioGroup>
  </Box>
```

## Common Use Cases

### Survey / Questionnaire Form

```tsx
function SurveyQuestion() {
  const [answer, setAnswer] = useState('');

  return (
    <FormControl>
      <FormLabel>How satisfied are you with our service?</FormLabel>
      <RadioGroup name="satisfaction" value={answer} onChange={(e) => setAnswer(e.target.value)}>
        <Radio value="very-satisfied" label="Very Satisfied" color="success" />
        <Radio value="satisfied" label="Satisfied" />
        <Radio value="neutral" label="Neutral" />
        <Radio value="dissatisfied" label="Dissatisfied" color="warning" />
        <Radio value="very-dissatisfied" label="Very Dissatisfied" color="danger" />
      </RadioGroup>
    </FormControl>
  );
}
```

### Payment Method Selection

```tsx
function PaymentMethodSelector() {
  const [method, setMethod] = useState('credit-card');

  return (
    <FormControl>
      <FormLabel>Payment Method</FormLabel>
      <RadioGroup name="payment" value={method} onChange={(e) => setMethod(e.target.value)} sx={{ gap: 1.5 }}>
        {[
          { value: 'credit-card', label: 'Credit Card' },
          { value: 'bank-transfer', label: 'Bank Transfer' },
          { value: 'paypal', label: 'PayPal' },
        ].map((option) => (
          <Sheet key={option.value} variant="outlined" sx={{ p: 2, borderRadius: 'md' }}>
            <Radio
              overlay
              value={option.value}
              label={option.label}
              slotProps={{
                action: ({ checked }) => ({
                  sx: {
                    ...(checked && {
                      '--variant-borderWidth': '2px',
                      borderColor: 'primary.500',
                    }),
                  },
                }),
              }}
            />
          </Sheet>
        ))}
      </RadioGroup>
    </FormControl>
  );
}
```

### Shipping Speed Selection

```tsx
function ShippingOptions() {
  const [shipping, setShipping] = useState('standard');

  return (
    <FormControl>
      <FormLabel>Shipping Speed</FormLabel>
      <RadioGroup name="shipping" value={shipping} onChange={(e) => setShipping(e.target.value)}>
        <Radio value="standard" label="Standard (5-7 business days) - Free" />
        <Radio value="express" label="Express (2-3 business days) - $9.99" />
        <Radio value="overnight" label="Overnight (next day) - $24.99" />
      </RadioGroup>
    </FormControl>
  );
}
```

## Best Practices

1. **Always use RadioGroup**: Wrap Radio buttons in a `RadioGroup` to ensure proper grouping, keyboard navigation, and mutual exclusivity.

```tsx
// ✅ Wrapped in RadioGroup
<RadioGroup name="options" value={value} onChange={handleChange}>
  <Radio value="a" label="Option A" />
  <Radio value="b" label="Option B" />
</RadioGroup>

// ❌ Standalone radios without a group
<Radio name="options" value="a" label="Option A" />
<Radio name="options" value="b" label="Option B" />
```

2. **Provide clear labels**: Every radio button must have a visible label or an `aria-label` to describe its purpose.

```tsx
// ✅ Descriptive label
<Radio value="monthly" label="Monthly billing ($10/month)" />

// ❌ Vague label
<Radio value="monthly" label="Option 1" />
```

3. **Set a default selection**: Pre-select the most common or recommended option using `defaultValue` or a controlled `value` to reduce user effort.

```tsx
// ✅ Sensible default
<RadioGroup defaultValue="standard" name="shipping">
  <Radio value="standard" label="Standard Shipping" />
  <Radio value="express" label="Express Shipping" />
</RadioGroup>
```

4. **Limit options to 2-7 items**: If more than 7 options exist, consider using a Select or Autocomplete component instead.

5. **Use vertical layout by default**: Vertical lists are easier to scan. Only use horizontal (`orientation="horizontal"`) when options are very short (e.g., segmented controls).

## Props and Customization

### Key Props

| Prop             | Type                                                           | Default      | Description                                   |
| ---------------- | -------------------------------------------------------------- | ------------ | --------------------------------------------- |
| `checked`        | `boolean`                                                      | -            | Whether the radio is selected (controlled)    |
| `defaultChecked` | `boolean`                                                      | `false`      | Initial selected state (uncontrolled)         |
| `onChange`       | `(event: ChangeEvent<HTMLInputElement>) => void`               | -            | Callback when the state changes               |
| `label`          | `ReactNode`                                                    | -            | Label content displayed next to the radio     |
| `value`          | `string`                                                       | -            | Value attribute for form submission           |
| `name`           | `string`                                                       | -            | Groups radios together for mutual exclusivity |
| `color`          | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'primary'`  | Color scheme                                  |
| `size`           | `'sm' \| 'md' \| 'lg'`                                         | `'md'`       | Radio button size                             |
| `variant`        | `'solid' \| 'soft' \| 'outlined' \| 'plain'`                   | `'outlined'` | Visual style                                  |
| `disabled`       | `boolean`                                                      | `false`      | Disables the radio button                     |
| `overlay`        | `boolean`                                                      | `false`      | Extends clickable area to parent container    |
| `disableIcon`    | `boolean`                                                      | `false`      | Hides the radio icon                          |
| `checkedIcon`    | `ReactNode`                                                    | -            | Custom icon for the checked state             |
| `sx`             | `SxProps`                                                      | -            | Custom styles using the MUI system            |

> **Note**: RadioButton also accepts all Joy UI Radio props and Framer Motion props.

## Accessibility

- **Keyboard navigation**: Users can move between options using `Arrow Up` / `Arrow Down` (vertical) or `Arrow Left` / `Arrow Right` (horizontal). `Space` selects the focused option.
- **ARIA roles**: `RadioGroup` renders with `role="radiogroup"`, and each `Radio` renders with `role="radio"` and `aria-checked` reflecting its state.
- **Labeling**: Always connect a `FormLabel` to the `RadioGroup` via `aria-labelledby`, or provide an `aria-label` directly on the group so screen readers can announce the group purpose.
- **Focus management**: When using `overlay` or `disableIcon` patterns, ensure the interactive area is clearly communicated -- the `overlay` prop extends the clickable area to the parent container, which is also reflected in focus styling.
