# Combobox

> Picks one value from a long list by typing to search it.

A combobox is a text field with a list: people type to narrow the list, then pick one value with the mouse or the keyboard.

## When to use

- Use it for more than 15 options, or whenever people know what they look for, such as an artist, a song or a company.
- Use a [Select](https://design.sosialoka.tech/components/select/) for 4 to 15 options, and a [Radio Group](https://design.sosialoka.tech/components/radio-group/) for 2 or 3.
- Write the empty text for the list, such as "Artis tidak ditemukan.", so people know the search worked.

**Searching on the server.** When the list lives in the backend, search as people type: wait about 300ms after the last key, keep the previous results while the next ones load, and show a [Spinner](https://design.sosialoka.tech/components/spinner/) in the list. The backend decides what matches.

_Live preview of the React and Vue versions: https://design.sosialoka.tech/components/combobox/_

## Anatomy

1. Input to type in
2. Typed text and caret
3. Matching option
4. List

1. **Input**: a text field on `radius-md` with an `input` border, `h-9` tall.
2. **List**: a popup on `popover` with a `border`, `radius-lg` and `shadow-lg`, as wide as the input.
3. **Item**: `radius-md`; the highlighted item is `accent` and the chosen one has a check icon.
4. **Empty text**: shown when nothing matches.

## Variants

There is one style. React also has chips (`ComboboxChips`) for picking several values.

## Props

| React | Vue | Flutter | Type | Default | Use |
| --- | --- | --- | --- | --- | --- |
| `items` on `Combobox` | `ComboboxItem` children | `options` on `ShadSelect.withSearch` | list | none | The options. |
| `value` / `defaultValue` | `v-model` | `initialValue` | value | none | The chosen value. |
| `onValueChange` | `@update:model-value` | `onChanged` | function | none | Runs when a value is picked. |
| `placeholder` on `ComboboxInput` | `placeholder` on `ComboboxInput` | `placeholder` | text | none | Shown before a choice. |
| `ComboboxEmpty` | `ComboboxEmpty` | an empty row in `options` | text | none | Says nothing matched. |
| `onInputValueChange` | `@update:model-value` on `ComboboxInput` | `onSearchChanged` | function | none | Runs as people type, for server search. |

## Code

**React**
```tsx
import { useId } from "react"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxList,
} from "@/components/ui/combobox"
import { Field, FieldLabel } from "@/components/ui/field"

const artists = ["Rara Senandika", "Bima Laras", "Nada Kirana", "Arka Wening", "Sinta Maharani", "Raka Pratama"]

export default function ComboboxDemo() {
  const id = useId()
  return (
    <Field className="w-full max-w-xs">
      <FieldLabel htmlFor={`${id}-artist`}>Artis</FieldLabel>
      <Combobox items={artists}>
        <ComboboxInput id={`${id}-artist`} placeholder="Pilih artis" />
        <ComboboxContent>
          <ComboboxEmpty>Artis tidak ditemukan.</ComboboxEmpty>
          <ComboboxList>
            {(artist: string) => (
              <ComboboxItem key={artist} value={artist}>
                {artist}
              </ComboboxItem>
            )}
          </ComboboxList>
        </ComboboxContent>
      </Combobox>
    </Field>
  )
}
```

**Vue**
```vue
<script setup lang="ts">
import { ref, useId } from "vue"
import { CheckIcon } from "@lucide/vue"
import {
  Combobox,
  ComboboxAnchor,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxList,
} from "@/components/ui/combobox"
import { Field, FieldLabel } from "@/components/ui/field"

const artists = ["Rara Senandika", "Bima Laras", "Nada Kirana", "Arka Wening", "Sinta Maharani", "Raka Pratama"]
const id = useId()
const artist = ref<string>()
</script>

<template>
  <Field class="w-full max-w-xs">
    <FieldLabel :for="`${id}-artist`">Artis</FieldLabel>
    <Combobox v-model="artist">
      <ComboboxAnchor>
        <ComboboxInput :id="`${id}-artist`" placeholder="Pilih artis" :display-value="(value: string) => value ?? ''" />
      </ComboboxAnchor>
      <ComboboxList>
        <ComboboxEmpty>Artis tidak ditemukan.</ComboboxEmpty>
        <ComboboxItem v-for="name in artists" :key="name" :value="name">
          {{ name }}
          <ComboboxItemIndicator>
            <CheckIcon />
          </ComboboxItemIndicator>
        </ComboboxItem>
      </ComboboxList>
    </Combobox>
  </Field>
</template>
```

**Flutter**
```dart
import 'package:flutter/widgets.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

const artists = ['Rara Senandika', 'Bima Laras', 'Nada Kirana', 'Arka Wening', 'Sinta Maharani', 'Raka Pratama'];

class ComboboxDemo extends StatefulWidget {
  const ComboboxDemo({super.key});

  @override
  State<ComboboxDemo> createState() => _ComboboxDemoState();
}

class _ComboboxDemoState extends State<ComboboxDemo> {
  String search = '';

  @override
  Widget build(BuildContext context) {
    final matches = artists.where((a) => a.toLowerCase().contains(search.toLowerCase())).toList();
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      spacing: 8,
      children: [
        Text('Artis', style: ShadTheme.of(context).textTheme.small),
        ShadSelect<String>.withSearch(
          minWidth: 280,
          placeholder: const Text('Pilih artis'),
          searchPlaceholder: const Text('Cari artis'),
          onSearchChanged: (value) => setState(() => search = value),
          options: [
            if (matches.isEmpty)
              const Padding(padding: EdgeInsets.symmetric(vertical: 24), child: Text('Artis tidak ditemukan.')),
            for (final artist in matches) ShadOption(value: artist, child: Text(artist)),
          ],
          selectedOptionBuilder: (context, value) => Text(value),
        ),
      ],
    );
  }
}
```

## Install

**React**
```bash
npx shadcn@latest add https://design.sosialoka.tech/r/react/combobox.json
```

**Vue**
```bash
npx shadcn-vue@latest add https://design.sosialoka.tech/r/vue/combobox.json
```

## Accessibility

- The input has `role="combobox"` and a visible label; the list has `role="listbox"` and its items `role="option"`.
- Typing filters the list. Arrow keys move through the items, Enter picks one, and Escape closes the list without changing the value.
- The empty text is read when nothing matches.
