# Select

Pilihan dropdown memakai select native yang di-styling, lengkap dengan label, petunjuk, dan pesan error.

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

## Kapan dipakai

Memilih satu nilai dari daftar pendek sampai sedang, misalnya kota, peran, atau negara.

- Untuk dua sampai lima pilihan yang perlu terlihat semua, pakai Radio Group
- Tambahkan option kosong sebagai placeholder kalau pilihan belum wajib terisi

## Kode

### Blade

Simpan di `resources/views/components/markas/select.blade.php`. Tanpa dependensi tambahan.

```blade
@props([
    'label' => null,
    'hint' => null,
    'error' => null,
])

@php
    $wrapper = 'grid gap-1.5';
    $labelClass = 'text-sm font-medium text-ink';
    $control = 'relative';
    $field = 'h-10 w-full cursor-pointer appearance-none rounded-md border border-line bg-surface pr-9 pl-3 text-sm text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none';
    $icon = 'pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted';
    $hintClass = 'text-sm text-muted';
    $errorClass = 'text-sm text-danger';

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

<div class="{{ $wrapper }}">
    @if ($label)
        <label for="{{ $id }}" class="{{ $labelClass }}">{{ $label }}</label>
    @endif
    <div class="{{ $control }}">
        <select {{ $attributes->merge(['id' => $id, 'aria-invalid' => $error ? 'true' : null, 'aria-describedby' => $describedBy])->class([$field]) }}>
            {{ $slot }}
        </select>
        <svg class="{{ $icon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
    </div>
    @if ($error)
        <p id="{{ $id }}-error" class="{{ $errorClass }}">{{ $error }}</p>
    @elseif ($hint)
        <p id="{{ $id }}-hint" class="{{ $hintClass }}">{{ $hint }}</p>
    @endif
</div>
```

```blade
<x-markas.select name="kota" label="Kota" hint="Pilih kota domisili.">
    <option value="jakarta">Jakarta</option>
    <option value="bandung" @selected(old('kota') === 'bandung')>Bandung</option>
</x-markas.select>
```

### React

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

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

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full cursor-pointer appearance-none rounded-md border border-line bg-surface pr-9 pl-3 text-sm text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const icon =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

export type SelectProps = ComponentProps<"select"> & {
  label?: ReactNode;
  hint?: ReactNode;
  error?: ReactNode;
};

export function Select({
  label,
  hint,
  error,
  id,
  className,
  children,
  ...props
}: SelectProps) {
  const generatedId = useId();
  const selectId = id ?? generatedId;
  const describedBy = error
    ? `${selectId}-error`
    : hint
      ? `${selectId}-hint`
      : undefined;

  return (
    <div className={wrapper}>
      {label && (
        <label htmlFor={selectId} className={labelClass}>
          {label}
        </label>
      )}
      <div className={control}>
        <select
          id={selectId}
          aria-invalid={error ? true : undefined}
          aria-describedby={describedBy}
          className={cx(field, className)}
          {...props}
        >
          {children}
        </select>
        <svg
          className={icon}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </div>
      {error ? (
        <p id={`${selectId}-error`} className={errorClass}>
          {error}
        </p>
      ) : hint ? (
        <p id={`${selectId}-hint`} className={hintClass}>
          {hint}
        </p>
      ) : null}
    </div>
  );
}
```

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

<Select name="kota" label="Kota" defaultValue="bandung">
  <option value="jakarta">Jakarta</option>
  <option value="bandung">Bandung</option>
</Select>;
```

### Vue

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

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

defineOptions({ inheritAttrs: false });

const props = defineProps<{
  label?: string;
  hint?: string;
  error?: string;
  id?: string;
}>();
const model = defineModel<string>();

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full cursor-pointer appearance-none rounded-md border border-line bg-surface pr-9 pl-3 text-sm text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const icon =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";

const generatedId = useId();
const selectId = computed(() => props.id ?? generatedId);
// Tanpa v-model, Vue mengosongkan <select>. Samakan dengan Blade dan React:
// pakai opsi yang ditandai selected, atau opsi pertama, seperti perilaku native.
const select = useTemplateRef<HTMLSelectElement>("select");
onMounted(() => {
  if (model.value !== undefined || !select.value) return;
  const options = [...select.value.options];
  const initial =
    options.find((option) => option.defaultSelected) ?? options[0];
  if (initial) model.value = initial.value;
});

const describedBy = computed(() =>
  props.error
    ? `${selectId.value}-error`
    : props.hint
      ? `${selectId.value}-hint`
      : undefined,
);
</script>

<template>
  <div :class="wrapper">
    <label v-if="props.label" :for="selectId" :class="labelClass">{{
      props.label
    }}</label>
    <div :class="control">
      <select
        :id="selectId"
        ref="select"
        v-model="model"
        :aria-invalid="props.error ? 'true' : undefined"
        :aria-describedby="describedBy"
        :class="field"
        v-bind="$attrs"
      >
        <slot />
      </select>
      <svg
        :class="icon"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>
    <p v-if="props.error" :id="`${selectId}-error`" :class="errorClass">
      {{ props.error }}
    </p>
    <p v-else-if="props.hint" :id="`${selectId}-hint`" :class="hintClass">
      {{ props.hint }}
    </p>
  </div>
</template>
```

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

const kota = ref("bandung");
</script>

<template>
  <Select v-model="kota" name="kota" label="Kota">
    <option value="jakarta">Jakarta</option>
    <option value="bandung">Bandung</option>
  </Select>
</template>
```

### Svelte

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

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

  const wrapper = "grid gap-1.5";
  const labelClass = "text-sm font-medium text-ink";
  const control = "relative";
  const field =
    "h-10 w-full cursor-pointer appearance-none rounded-md border border-line bg-surface pr-9 pl-3 text-sm text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
  const icon =
    "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
  const hintClass = "text-sm text-muted";
  const errorClass = "text-sm text-danger";

  type Props = Omit<HTMLSelectAttributes, "value"> & {
    label?: string;
    hint?: string;
    error?: string;
    value?: string;
    children?: Snippet;
  };

  let {
    label,
    hint,
    error,
    id,
    value = $bindable(),
    class: className,
    children,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const selectId = $derived(id ?? generatedId);
  const describedBy = $derived(
    error ? `${selectId}-error` : hint ? `${selectId}-hint` : undefined,
  );
</script>

<div class={wrapper}>
  {#if label}
    <label for={selectId} class={labelClass}>{label}</label>
  {/if}
  <div class={control}>
    <select
      id={selectId}
      bind:value
      aria-invalid={error ? "true" : undefined}
      aria-describedby={describedBy}
      class={[field, className]}
      {...rest}
    >
      {@render children?.()}
    </select>
    <svg
      class={icon}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  </div>
  {#if error}
    <p id={`${selectId}-error`} class={errorClass}>{error}</p>
  {:else if hint}
    <p id={`${selectId}-hint`} class={hintClass}>{hint}</p>
  {/if}
</div>
```

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

  let kota = $state("bandung");
</script>

<Select bind:value={kota} name="kota" label="Kota">
  <option value="jakarta">Jakarta</option>
  <option value="bandung">Bandung</option>
</Select>
```

### Astro

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

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

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full cursor-pointer appearance-none rounded-md border border-line bg-surface pr-9 pl-3 text-sm text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const icon =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";

type Props = HTMLAttributes<"select"> & {
  label?: string;
  hint?: string;
  error?: string;
};

const { label, hint, error, id, class: className, ...rest } = Astro.props;
const selectId = id ?? `markas-select-${crypto.randomUUID().slice(0, 8)}`;
const describedBy = error
  ? `${selectId}-error`
  : hint
    ? `${selectId}-hint`
    : undefined;
---

<div class={wrapper}>
  {
    label && (
      <label for={selectId} class={labelClass}>
        {label}
      </label>
    )
  }
  <div class={control}>
    <select
      id={selectId}
      aria-invalid={error ? "true" : undefined}
      aria-describedby={describedBy}
      class:list={[field, className]}
      {...rest}
    >
      <slot />
    </select>
    <svg
      class={icon}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6"></path>
    </svg>
  </div>
  {
    error ? (
      <p id={`${selectId}-error`} class={errorClass}>
        {error}
      </p>
    ) : hint ? (
      <p id={`${selectId}-hint`} class={hintClass}>
        {hint}
      </p>
    ) : null
  }
</div>
```

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

<Select name="kota" label="Kota">
  <option value="jakarta">Jakarta</option>
  <option value="bandung" selected>Bandung</option>
</Select>
```

Tanpa script klien: select adalah elemen native.

### Angular

Simpan di `src/app/markas/select.component.ts`. Tanpa dependensi tambahan.

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

const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control = "relative";
const field =
  "h-10 w-full cursor-pointer appearance-none rounded-md border border-line bg-surface pr-9 pl-3 text-sm text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-danger motion-reduce:transition-none";
const icon =
  "pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";

let nextId = 0;

/**
 * Projected option and optgroup elements fill the native select. Host stays out of layout;
 * id, name, aria-label, and class move to the select, so the host attributes are cleared.
 */
@Component({
  selector: "markas-select",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "[attr.name]": "null",
    "[attr.aria-label]": "null",
  },
  template: `
    <div [class]="wrapper">
      @if (label()) {
        <label [for]="selectId()" [class]="labelClass">{{ label() }}</label>
      }
      <div [class]="control">
        <select
          #select
          [id]="selectId()"
          [disabled]="disabled()"
          [required]="required()"
          [attr.name]="name() ?? null"
          [attr.aria-label]="ariaLabel() ?? null"
          [attr.aria-invalid]="error() ? 'true' : null"
          [attr.aria-describedby]="describedBy()"
          [class]="fieldClass()"
          (change)="value.set(select.value)"
        >
          <ng-content />
        </select>
        <svg
          [class]="icon"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </div>
      @if (error()) {
        <p [id]="selectId() + '-error'" [class]="errorClass">{{ error() }}</p>
      } @else if (hint()) {
        <p [id]="selectId() + '-hint'" [class]="hintClass">{{ hint() }}</p>
      }
    </div>
  `,
})
export class Select {
  readonly label = input<string>();
  readonly hint = input<string>();
  readonly error = input<string>();
  readonly id = input<string>();
  readonly name = input<string>();
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly required = input(false, { transform: booleanAttribute });
  readonly ariaLabel = input<string | undefined>(undefined, {
    alias: "aria-label",
  });
  readonly userClass = input("", { alias: "class" });
  /** Two-way bindable with [(value)]. Without it the option marked selected (or the first) wins. */
  readonly value = model<string>();

  protected readonly wrapper = wrapper;
  protected readonly labelClass = labelClass;
  protected readonly control = control;
  protected readonly icon = icon;
  protected readonly hintClass = hintClass;
  protected readonly errorClass = errorClass;
  private readonly generatedId = `markas-select-${nextId++}`;
  protected readonly selectId = computed(() => this.id() ?? this.generatedId);
  protected readonly describedBy = computed(() =>
    this.error()
      ? `${this.selectId()}-error`
      : this.hint()
        ? `${this.selectId()}-hint`
        : null,
  );
  protected readonly fieldClass = computed(() =>
    [field, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly select =
    viewChild.required<ElementRef<HTMLSelectElement>>("select");

  constructor() {
    // Projected options exist only after render, so the value is applied afterwards.
    afterRenderEffect(() => {
      const value = this.value();
      if (value !== undefined) this.select().nativeElement.value = value;
    });
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import { Select } from "./markas/select.component";

@Component({
  selector: "app-alamat",
  imports: [Select],
  template: `
    <markas-select [(value)]="kota" name="kota" label="Kota">
      <option value="jakarta">Jakarta</option>
      <option value="bandung">Bandung</option>
    </markas-select>
  `,
})
export class Alamat {
  readonly kota = signal("bandung");
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `label` | `string` | - | Teks label yang terhubung ke select lewat for/id. |
| `hint` | `string` | - | Teks petunjuk di bawah select. Disembunyikan saat ada error. |
| `error` | `string` | - | Pesan error. Mengaktifkan aria-invalid dan border danger. |
| `slot / children` | `<option>` | - | Daftar elemen option (dan optgroup) native. |
| `value / defaultValue / v-model / bind:value` | `string` | - | Nilai terpilih. Blade dan Astro memakai atribut selected di option, React value atau defaultValue, Vue v-model, Svelte bind:value, Angular value atau [(value)]. |
| `id` | `string` | auto | Id select. Dibuat otomatis kalau kosong. |

## Aksesibilitas

- Memakai elemen select native, jadi keyboard dan screen reader bekerja tanpa JavaScript.
- Label terhubung lewat for dan id, petunjuk dan error lewat aria-describedby.
- Ikon panah disembunyikan dari screen reader dan tidak menangkap klik.

## Catatan

- Atribut tambahan (`name`, `required`, `multiple`, `class`) diteruskan ke elemen `<select>`.
- Tanpa `v-model`, versi Vue memilih option yang ditandai `selected`, atau option pertama, sama seperti Blade dan React.
- Komponen ini tidak punya teks bawaan. Semua teks berasal dari prop dan option, jadi cukup tulis dalam Bahasa Indonesia.
