# Radio Group

Kelompok radio native dalam fieldset dan legend untuk memilih satu dari beberapa opsi.

- Kategori: Form
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/radio-group.json
- CLI: `npx markasui@latest add radio-group`

## Kapan dipakai

Memilih tepat satu dari dua sampai lima opsi yang perlu terlihat semua, misalnya paket langganan.

- Value opsi hanya huruf kecil, angka, tanda hubung, atau underscore karena dipakai sebagai id
- Untuk daftar panjang pakai Select

## Kode

### Blade

Simpan di `resources/views/components/markas/radio-group.blade.php`. Tanpa dependensi tambahan.

```blade
@props([
    'name',
    'label' => null,
    'options' => [],
    'value' => null,
    'orientation' => 'vertical',
])

@php
    $root = 'min-w-0';
    $legendClass = 'mb-3 text-sm font-medium text-ink';
    $orientations = [
        'vertical' => 'grid gap-3',
        'horizontal' => 'flex flex-wrap gap-x-6 gap-y-3',
    ];
    $item = 'flex items-start gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50';
    $control = 'relative mt-0.5 flex size-4 shrink-0';
    $radio = 'peer size-4 shrink-0 cursor-pointer appearance-none rounded-full border border-faint bg-surface transition-colors duration-150 ease-out checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none';
    $dot = 'pointer-events-none absolute inset-1 rounded-full bg-on-primary opacity-0 peer-checked:opacity-100';
    $text = 'grid gap-0.5';
    $labelClass = 'text-sm font-medium text-ink';
    $descriptionClass = 'text-sm text-muted';

    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-radio-group|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $name).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $id = $attributes->get('id') ?? 'markas-radio-group-'.hash('xxh32', $idKey.$idIndex);
    // wire:model and x-model go on every radio, the rest on the fieldset.
    $model = $attributes->whereStartsWith(['wire:model', 'x-model']);
@endphp

<fieldset {{ $attributes->whereDoesntStartWith(['wire:model', 'x-model'])->merge(['id' => $id])->class([$root]) }}>
    @if ($label)
        <legend class="{{ $legendClass }}">{{ $label }}</legend>
    @endif
    <div class="{{ $orientations[$orientation] }}">
        @foreach ($options as $option)
            @php
                $optionId = $id.'-'.$option['value'];
                $description = $option['description'] ?? null;
            @endphp
            <div class="{{ $item }}">
                <span class="{{ $control }}">
                    <input
                        type="radio"
                        id="{{ $optionId }}"
                        name="{{ $name }}"
                        value="{{ $option['value'] }}"
                        @checked((string) $option['value'] === (string) $value)
                        @if ($description) aria-describedby="{{ $optionId }}-description" @endif
                        class="{{ $radio }}"
                        {{ $model }}
                    />
                    <span class="{{ $dot }}" aria-hidden="true"></span>
                </span>
                <div class="{{ $text }}">
                    <label for="{{ $optionId }}" class="{{ $labelClass }}">{{ $option['label'] }}</label>
                    @if ($description)
                        <p id="{{ $optionId }}-description" class="{{ $descriptionClass }}">{{ $description }}</p>
                    @endif
                </div>
            </div>
        @endforeach
    </div>
</fieldset>
```

```blade
<x-markas.radio-group
    name="paket"
    label="Paket langganan"
    :value="old('paket', 'pro')"
    :options="[
        ['value' => 'gratis', 'label' => 'Gratis', 'description' => 'Untuk proyek pribadi.'],
        ['value' => 'pro', 'label' => 'Pro'],
    ]"
/>
```

### Livewire

```blade
<x-markas.radio-group name="plan" wire:model.live="plan" :options="$plans" />
```

`wire:model` (dan `x-model`) disalin ke setiap radio, jadi Livewire membaca nilai yang dicentang. Atribut lain tetap di `fieldset`.

### React

Simpan di `src/components/markas/RadioGroup.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import { useId, type ComponentProps, type ReactNode } from "react";

const root = "min-w-0";
const legendClass = "mb-3 text-sm font-medium text-ink";
const orientations = {
  vertical: "grid gap-3",
  horizontal: "flex flex-wrap gap-x-6 gap-y-3",
};
const item =
  "flex items-start gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative mt-0.5 flex size-4 shrink-0";
const radio =
  "peer size-4 shrink-0 cursor-pointer appearance-none rounded-full border border-faint bg-surface transition-colors duration-150 ease-out checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const dot =
  "pointer-events-none absolute inset-1 rounded-full bg-on-primary opacity-0 peer-checked:opacity-100";
const text = "grid gap-0.5";
const labelClass = "text-sm font-medium text-ink";
const descriptionClass = "text-sm text-muted";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

export type RadioOption = {
  value: string;
  label: ReactNode;
  description?: ReactNode;
};

export type RadioGroupProps = Omit<
  ComponentProps<"fieldset">,
  "defaultValue"
> & {
  name: string;
  options: RadioOption[];
  label?: ReactNode;
  value?: string;
  defaultValue?: string;
  orientation?: keyof typeof orientations;
  onValueChange?: (value: string) => void;
};

export function RadioGroup({
  name,
  options,
  label,
  value,
  defaultValue,
  orientation = "vertical",
  onValueChange,
  id,
  className,
  ...props
}: RadioGroupProps) {
  const generatedId = useId();
  const groupId = id ?? generatedId;
  const controlled = value !== undefined;

  return (
    <fieldset id={groupId} className={cx(root, className)} {...props}>
      {label && <legend className={legendClass}>{label}</legend>}
      <div className={orientations[orientation]}>
        {options.map((option) => {
          const optionId = `${groupId}-${option.value}`;
          return (
            <div key={option.value} className={item}>
              <span className={control}>
                <input
                  type="radio"
                  id={optionId}
                  name={name}
                  value={option.value}
                  checked={controlled ? option.value === value : undefined}
                  defaultChecked={
                    controlled ? undefined : option.value === defaultValue
                  }
                  aria-describedby={
                    option.description ? `${optionId}-description` : undefined
                  }
                  onChange={() => onValueChange?.(option.value)}
                  className={radio}
                />
                <span className={dot} aria-hidden="true" />
              </span>
              <div className={text}>
                <label htmlFor={optionId} className={labelClass}>
                  {option.label}
                </label>
                {option.description && (
                  <p
                    id={`${optionId}-description`}
                    className={descriptionClass}
                  >
                    {option.description}
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </fieldset>
  );
}
```

```tsx
import { RadioGroup } from "@/components/markas/RadioGroup";

<RadioGroup
  name="paket"
  label="Paket langganan"
  defaultValue="pro"
  onValueChange={(value) => console.log(value)}
  options={[
    { value: "gratis", label: "Gratis", description: "Untuk proyek pribadi." },
    { value: "pro", label: "Pro" },
  ]}
/>;
```

### Vue

Simpan di `src/components/markas/RadioGroup.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import { computed, useId } from "vue";

export type RadioOption = {
  value: string;
  label: string;
  description?: string;
};

const props = withDefaults(
  defineProps<{
    name: string;
    options: RadioOption[];
    label?: string;
    orientation?: "vertical" | "horizontal";
    id?: string;
  }>(),
  { label: undefined, id: undefined, orientation: "vertical" },
);
const model = defineModel<string>();

const root = "min-w-0";
const legendClass = "mb-3 text-sm font-medium text-ink";
const orientations = {
  vertical: "grid gap-3",
  horizontal: "flex flex-wrap gap-x-6 gap-y-3",
};
const item =
  "flex items-start gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative mt-0.5 flex size-4 shrink-0";
const radio =
  "peer size-4 shrink-0 cursor-pointer appearance-none rounded-full border border-faint bg-surface transition-colors duration-150 ease-out checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const dot =
  "pointer-events-none absolute inset-1 rounded-full bg-on-primary opacity-0 peer-checked:opacity-100";
const text = "grid gap-0.5";
const labelClass = "text-sm font-medium text-ink";
const descriptionClass = "text-sm text-muted";

const generatedId = useId();
const groupId = computed(() => props.id ?? generatedId);
</script>

<template>
  <fieldset :id="groupId" :class="root">
    <legend v-if="props.label" :class="legendClass">{{ props.label }}</legend>
    <div :class="orientations[props.orientation]">
      <div v-for="option in props.options" :key="option.value" :class="item">
        <span :class="control">
          <input
            :id="`${groupId}-${option.value}`"
            v-model="model"
            type="radio"
            :name="props.name"
            :value="option.value"
            :aria-describedby="
              option.description
                ? `${groupId}-${option.value}-description`
                : undefined
            "
            :class="radio"
          />
          <span :class="dot" aria-hidden="true" />
        </span>
        <div :class="text">
          <label :for="`${groupId}-${option.value}`" :class="labelClass">{{
            option.label
          }}</label>
          <p
            v-if="option.description"
            :id="`${groupId}-${option.value}-description`"
            :class="descriptionClass"
          >
            {{ option.description }}
          </p>
        </div>
      </div>
    </div>
  </fieldset>
</template>
```

```vue
<script setup lang="ts">
import { ref } from "vue";
import RadioGroup from "@/components/markas/RadioGroup.vue";

const paket = ref("pro");
</script>

<template>
  <RadioGroup
    v-model="paket"
    name="paket"
    label="Paket langganan"
    :options="[
      {
        value: 'gratis',
        label: 'Gratis',
        description: 'Untuk proyek pribadi.',
      },
      { value: 'pro', label: 'Pro' },
    ]"
  />
</template>
```

### Svelte

Simpan di `src/lib/components/markas/RadioGroup.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts">
  import type { HTMLFieldsetAttributes } from "svelte/elements";

  const root = "min-w-0";
  const legendClass = "mb-3 text-sm font-medium text-ink";
  const orientations = {
    vertical: "grid gap-3",
    horizontal: "flex flex-wrap gap-x-6 gap-y-3",
  };
  const item =
    "flex items-start gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
  const control = "relative mt-0.5 flex size-4 shrink-0";
  const radio =
    "peer size-4 shrink-0 cursor-pointer appearance-none rounded-full border border-faint bg-surface transition-colors duration-150 ease-out checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
  const dot =
    "pointer-events-none absolute inset-1 rounded-full bg-on-primary opacity-0 peer-checked:opacity-100";
  const text = "grid gap-0.5";
  const labelClass = "text-sm font-medium text-ink";
  const descriptionClass = "text-sm text-muted";

  type RadioOption = {
    value: string;
    label: string;
    description?: string;
  };

  type Props = HTMLFieldsetAttributes & {
    name: string;
    options: RadioOption[];
    label?: string;
    /** Selected option, bindable with bind:value. */
    value?: string;
    orientation?: keyof typeof orientations;
  };

  let {
    name,
    options,
    label,
    value = $bindable(),
    orientation = "vertical",
    id,
    class: className,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const groupId = $derived(id ?? generatedId);
</script>

<fieldset id={groupId} class={[root, className]} {...rest}>
  {#if label}
    <legend class={legendClass}>{label}</legend>
  {/if}
  <div class={orientations[orientation]}>
    {#each options as option (option.value)}
      {@const optionId = `${groupId}-${option.value}`}
      <div class={item}>
        <span class={control}>
          <input
            type="radio"
            id={optionId}
            {name}
            value={option.value}
            bind:group={value}
            aria-describedby={option.description
              ? `${optionId}-description`
              : undefined}
            class={radio}
          />
          <span class={dot} aria-hidden="true"></span>
        </span>
        <div class={text}>
          <label for={optionId} class={labelClass}>{option.label}</label>
          {#if option.description}
            <p id={`${optionId}-description`} class={descriptionClass}>
              {option.description}
            </p>
          {/if}
        </div>
      </div>
    {/each}
  </div>
</fieldset>
```

```svelte
<script lang="ts">
  import RadioGroup from "$lib/components/markas/RadioGroup.svelte";

  let plan = $state("pro");
</script>

<RadioGroup
  bind:value={plan}
  name="plan"
  label="Paket langganan"
  options={[
    { value: "free", label: "Gratis", description: "Untuk proyek pribadi." },
    { value: "pro", label: "Pro" },
  ]}
/>
```

### Astro

Simpan di `src/components/markas/RadioGroup.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root = "min-w-0";
const legendClass = "mb-3 text-sm font-medium text-ink";
const orientations = {
  vertical: "grid gap-3",
  horizontal: "flex flex-wrap gap-x-6 gap-y-3",
};
const item =
  "flex items-start gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative mt-0.5 flex size-4 shrink-0";
const radio =
  "peer size-4 shrink-0 cursor-pointer appearance-none rounded-full border border-faint bg-surface transition-colors duration-150 ease-out checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const dot =
  "pointer-events-none absolute inset-1 rounded-full bg-on-primary opacity-0 peer-checked:opacity-100";
const text = "grid gap-0.5";
const labelClass = "text-sm font-medium text-ink";
const descriptionClass = "text-sm text-muted";

type RadioOption = {
  value: string;
  label: string;
  description?: string;
};

type Props = HTMLAttributes<"fieldset"> & {
  name: string;
  options: RadioOption[];
  label?: string;
  value?: string;
  orientation?: keyof typeof orientations;
};

const {
  name,
  options,
  label,
  value,
  orientation = "vertical",
  id,
  class: className,
  ...rest
} = Astro.props;
const groupId = id ?? `markas-radio-group-${crypto.randomUUID().slice(0, 8)}`;
---

<fieldset id={groupId} class:list={[root, className]} {...rest}>
  {label && <legend class={legendClass}>{label}</legend>}
  <div class={orientations[orientation]}>
    {
      options.map((option) => {
        const optionId = `${groupId}-${option.value}`;
        return (
          <div class={item}>
            <span class={control}>
              <input
                type="radio"
                id={optionId}
                name={name}
                value={option.value}
                checked={option.value === value}
                aria-describedby={
                  option.description ? `${optionId}-description` : undefined
                }
                class={radio}
              />
              <span class={dot} aria-hidden="true" />
            </span>
            <div class={text}>
              <label for={optionId} class={labelClass}>
                {option.label}
              </label>
              {option.description && (
                <p id={`${optionId}-description`} class={descriptionClass}>
                  {option.description}
                </p>
              )}
            </div>
          </div>
        );
      })
    }
  </div>
</fieldset>
```

```astro
---
import RadioGroup from "@/components/markas/RadioGroup.astro";
---

<RadioGroup
  name="plan"
  label="Paket langganan"
  value="pro"
  options={[
    { value: "free", label: "Gratis", description: "Untuk proyek pribadi." },
    { value: "pro", label: "Pro" },
  ]}
/>
```

Tanpa script klien: opsinya radio native.

### Angular

Simpan di `src/app/markas/radio-group.component.ts`. Tanpa dependensi tambahan.

```ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  model,
} from "@angular/core";

const root = "min-w-0";
const legendClass = "mb-3 text-sm font-medium text-ink";
const orientations = {
  vertical: "grid gap-3",
  horizontal: "flex flex-wrap gap-x-6 gap-y-3",
};
const item =
  "flex items-start gap-3 has-disabled:cursor-not-allowed has-disabled:opacity-50";
const control = "relative mt-0.5 flex size-4 shrink-0";
const radio =
  "peer size-4 shrink-0 cursor-pointer appearance-none rounded-full border border-faint bg-surface transition-colors duration-150 ease-out checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed motion-reduce:transition-none";
const dot =
  "pointer-events-none absolute inset-1 rounded-full bg-on-primary opacity-0 peer-checked:opacity-100";
const text = "grid gap-0.5";
const labelClass = "text-sm font-medium text-ink";
const descriptionClass = "text-sm text-muted";

export type RadioOption = {
  value: string;
  label: string;
  description?: string;
};

let nextId = 0;

/**
 * Host stays out of layout (display: contents). id, disabled, and class move to the fieldset,
 * so the host attributes are cleared.
 */
@Component({
  selector: "markas-radio-group",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "[attr.name]": "null",
    "[attr.label]": "null",
    "[attr.disabled]": "null",
  },
  template: `
    <fieldset [id]="groupId()" [class]="rootClass()" [disabled]="disabled()">
      @if (label()) {
        <legend [class]="legendClass">{{ label() }}</legend>
      }
      <div [class]="orientations[orientation()]">
        @for (option of options(); track option.value) {
          @let optionId = groupId() + "-" + option.value;
          <div [class]="item">
            <span [class]="control">
              <input
                type="radio"
                [id]="optionId"
                [name]="name()"
                [value]="option.value"
                [checked]="option.value === value()"
                [attr.aria-describedby]="
                  option.description ? optionId + '-description' : null
                "
                [class]="radio"
                (change)="value.set(option.value)"
              />
              <span [class]="dot" aria-hidden="true"></span>
            </span>
            <div [class]="text">
              <label [for]="optionId" [class]="labelClass">{{
                option.label
              }}</label>
              @if (option.description) {
                <p [id]="optionId + '-description'" [class]="descriptionClass">
                  {{ option.description }}
                </p>
              }
            </div>
          </div>
        }
      </div>
    </fieldset>
  `,
})
export class RadioGroup {
  readonly name = input.required<string>();
  readonly options = input.required<RadioOption[]>();
  readonly label = input<string>();
  readonly orientation = input<keyof typeof orientations>("vertical");
  readonly id = input<string>();
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly userClass = input("", { alias: "class" });
  /** Selected option, two-way bindable with [(value)]. */
  readonly value = model<string>();

  protected readonly legendClass = legendClass;
  protected readonly orientations = orientations;
  protected readonly item = item;
  protected readonly control = control;
  protected readonly radio = radio;
  protected readonly dot = dot;
  protected readonly text = text;
  protected readonly labelClass = labelClass;
  protected readonly descriptionClass = descriptionClass;
  private readonly generatedId = `markas-radio-group-${nextId++}`;
  protected readonly groupId = computed(() => this.id() ?? this.generatedId);
  protected readonly rootClass = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
}
```

```ts
import { Component, signal } from "@angular/core";
import { RadioGroup } from "./markas/radio-group.component";

@Component({
  selector: "app-tagihan",
  imports: [RadioGroup],
  template: `
    <markas-radio-group
      [(value)]="plan"
      name="plan"
      label="Paket langganan"
      [options]="plans"
    />
  `,
})
export class Tagihan {
  readonly plan = signal<string | undefined>("pro");
  readonly plans = [
    { value: "free", label: "Gratis", description: "Untuk proyek pribadi." },
    { value: "pro", label: "Pro" },
  ];
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `name` | `string` | required | Atribut name untuk semua radio di grup. |
| `options` | `{ value, label, description? }[]` | [] | Daftar opsi. Value dipakai juga sebagai bagian id. |
| `label` | `string` | - | Judul grup, dirender sebagai legend. |
| `value / defaultValue / v-model / bind:value` | `string` | - | Opsi terpilih. Blade dan Astro memakai value, React value atau defaultValue, Vue v-model, Svelte bind:value, Angular value atau [(value)]. |
| `onValueChange` | `(value: string) => void` | - | Khusus React. Dipanggil dengan value opsi yang baru dipilih. |
| `orientation` | `"vertical" \| "horizontal"` | vertical | Susunan opsi: bertumpuk atau berjajar. |
| `id` | `string` | auto | Id fieldset, juga awalan id tiap radio. Dibuat otomatis kalau kosong. |

## Aksesibilitas

- Memakai fieldset dan legend sehingga judul grup dibacakan saat masuk ke radio.
- Radio native: Tab masuk ke opsi terpilih, panah memindah pilihan.
- Deskripsi opsi dihubungkan ke radio lewat aria-describedby.

## Catatan

- Atribut tambahan (`class`, `disabled`, `aria-*`) jatuh ke `<fieldset>`. `disabled` di fieldset menonaktifkan semua radio sekaligus.
- Value opsi dipakai sebagai bagian id, jadi pakai huruf kecil, angka, tanda hubung, atau underscore saja.
- Pakai `orientation="horizontal"` untuk opsi pendek yang berjajar.
- Komponen ini tidak punya teks bawaan. Cukup isi `label` serta `label` dan `description` tiap opsi dalam Bahasa Indonesia.
