Skip to main content

Combobox

Choose one collection item through an editable search input.

Props
Slots

Anatomy#

Combobox [component; no DOM]
├── control [slot]
│   ├── leading [slot]
│   ├── input [slot]
│   ├── clear [slot]
│   └── trigger [slot]
└── positioner [internal]
    └── content [slot]
        ├── listbox [slot]
        │   ├── group [slot]
        │   │   └── groupLabel [slot]
        │   ├── separator [slot]
        │   └── item [slot]
        │       ├── itemLeading [slot]
        │       ├── itemWrapper [slot]
        │       │   ├── itemLabel [slot]
        │       │   └── itemDescription [slot]
        │       └── itemIndicator [slot]
        └── empty [slot]

Combobox renders the portaled popup internally; the popup names are style slots, not attached parts.

Usage#

Use Combobox when users should type to find one item in a collection. Use Select for a non-editable choice, MultiSelect for several collection values, or BaseSelect to compose the listbox yourself.

import { Field, Combobox } from 'moraine'

export function Example() {
  return (
    <Field label="Fruit">
      <Combobox
        items={[
          { label: 'Apple', value: 'apple' },
          { label: 'Pear', value: 'pear' },
        ]}
        placeholder="Search fruit"
      />
    </Field>
  )
}

String items#

Pass strings when the label and value are identical. You can mix strings and objects at the root or inside a group. Whitespace is preserved, and an empty string is a valid value.

<Combobox items={['Apple', 'Banana']} defaultValue="Apple" />
<Combobox
  items={[
    'Apple',
    { value: 'pear', label: 'Pear' },
    { type: 'group', label: 'More fruit', items: ['Banana'] },
  ]}
/>

String items are converted to the same item shape used by callbacks: 'Apple' becomes { value: 'Apple', label: 'Apple' }. Object items keep their identity and custom fields. ComboboxT.NormalizedItem<TItem> is the callback item type. Item values must be unique. When two items share a value, the first one wins (including a string that collides with an object), and development builds log an error.

Value and query#

Pair value with onValueChange for controlled selection, or use defaultValue for an initial uncontrolled choice. value={undefined} keeps the selection uncontrolled; value={null} keeps it controlled and empty. onValueChange receives null when the selection is cleared, and inside a form field, clearing writes null.

While open, the input displays the query; while closed, it displays the selected item label. Query text is never committed as a value, and filtering never changes the selection. Use value / onValueChange for selection and searchValue / onSearchValueChange for query text. The query resets to '' when the popup finishes closing and after a native form reset; in controlled mode, onSearchValueChange('') reports these resets and you decide whether to apply them.

<Combobox
  items={frameworks}
  value={selected()}
  onValueChange={setSelected}
  searchValue={query()}
  onSearchValueChange={setQuery}
/>

Clear and loading#

clearable shows a clear button while there is a selected value or query text. Clearing resets the selection and the query, calls onValueChange(null) if a value existed, then onClear, and returns focus to the input. loading replaces the toggle icon with loadingIcon and disables the toggle button; typing and the clear button keep working.

Pointer opening#

By default, clicking inside the control focuses the input without opening the popup. The trailing chevron button toggles the popup, and typing non-blank text or pressing ArrowDown opens it. Set openOnControlClick to open the popup on any click on the control outside its buttons.

<Combobox items={items} placeholder="Click the chevron to open" />
<Combobox items={items} openOnControlClick placeholder="Click the field to open" />

Keyboard interaction#

Focus stays in the input; the highlighted option is exposed through aria-activedescendant.

Key Behavior
ArrowDown / ArrowUp Open the popup and move the highlight through enabled options
PageUp / PageDown Move the highlight by one page of options while open
Enter Open the popup, or commit the highlighted option while open
Escape Close the popup; with the popup closed and clearable, clear the value and query
Backspace / Delete With an empty input and clearable, clear the value
Tab Close the popup and move focus on
Home / End Move the text cursor; they never move the highlight

Virtualization#

Pass a virtualizer from createListVirtualizer when rendering the full collection makes opening or scrolling slow. Type it over ComboboxT.Row. Read the Virtualization guide for setup, row measurement, stable keys, and keyboard navigation.

<Combobox items={items} virtualizer={virtualizer} />

Examples#

Search a framework#

Filter a local collection as the user types. clearable removes the committed value and the query text.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'

const FRAMEWORKS: ComboboxT.Item[] = [
  { label: 'SolidJS', value: 'solid' },
  { label: 'React', value: 'react' },
  { label: 'Vue.js', value: 'vue' },
  { label: 'Svelte', value: 'svelte' },
  { label: 'Astro', value: 'astro' },
  { label: 'Next.js', value: 'next' },
  { label: 'Nuxt', value: 'nuxt' },
]

export function Basic() {
  return (
    <div class="max-w-xs w-full">
      <Combobox
        items={FRAMEWORKS}
        placeholder="Search framework..."
        leading="i-lucide:search"
        clearable
      />
    </div>
  )
}

Pick an issue status#

Put icon and description on each item when the option needs a status mark and secondary line.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'

const STATUSES: ComboboxT.Item[] = [
  {
    label: 'Backlog',
    value: 'backlog',
    icon: 'i-lucide:circle-dashed',
    description: 'Ideas and unprioritized tasks',
  },
  {
    label: 'Todo',
    value: 'todo',
    icon: 'i-lucide:circle',
    description: 'Ready to be picked up',
  },
  {
    label: 'In Progress',
    value: 'in-progress',
    icon: 'i-lucide:circle-dot',
    description: 'Work actively underway',
  },
  {
    label: 'In Review',
    value: 'review',
    icon: 'i-lucide:clock',
    description: 'PR open and waiting for review',
  },
  {
    label: 'Done',
    value: 'done',
    icon: 'i-lucide:check-circle-2',
    description: 'Completed and merged',
  },
  {
    label: 'Canceled',
    value: 'canceled',
    icon: 'i-lucide:x-circle',
    description: 'Discarded or not planned',
  },
]

export function CustomItems() {
  return (
    <div class="max-w-sm w-full space-y-2">
      <label class="text-xs text-muted-foreground font-medium block">Issue Status</label>
      <Combobox
        items={STATUSES}
        defaultValue="in-progress"
        placeholder="Filter status..."
        openOnControlClick
      />
    </div>
  )
}

Assign a teammate#

Search people by name; each item’s description shows the email and role. The default filter matches the label only. Set openOnControlClick to open the list as soon as the user clicks the control.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'

const USERS: ComboboxT.Item[] = [
  {
    label: 'Sarah Connor',
    value: 'sarah',
    icon: 'i-lucide:user',
    description: 'sarah@example.com · Engineering Lead',
  },
  {
    label: 'Alex Rivera',
    value: 'alex',
    icon: 'i-lucide:user',
    description: 'alex@example.com · Product Designer',
  },
  {
    label: 'Elena Rostova',
    value: 'elena',
    icon: 'i-lucide:user',
    description: 'elena@example.com · Frontend Engineer',
  },
  {
    label: 'David Kim',
    value: 'david',
    icon: 'i-lucide:user',
    description: 'david@example.com · DevOps Specialist',
  },
]

export function UserPicker() {
  return (
    <div class="max-w-sm w-full space-y-2">
      <label class="text-xs text-muted-foreground font-medium block">Assignee</label>
      <Combobox
        items={USERS}
        placeholder="Assign to teammate..."
        leading="i-lucide:user-plus"
        openOnControlClick
        clearable
      />
    </div>
  )
}

Match by contains or prefix#

filterMethod defaults to 'contains', which matches the query anywhere in the label. Set 'startsWith' or 'endsWith' to match only at that end of the label, or pass a predicate for custom matching.

import { Button, Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'
import { createSignal } from 'solid-js'

const CITIES: ComboboxT.Item[] = [
  { label: 'San Francisco', value: 'sf' },
  { label: 'San Jose', value: 'sj' },
  { label: 'Santa Clara', value: 'sc' },
  { label: 'Los Angeles', value: 'la' },
  { label: 'New York', value: 'ny' },
  { label: 'Boston', value: 'bos' },
]

export function FilterStrategies() {
  const [strategy, setStrategy] = createSignal<'contains' | 'startsWith'>('contains')

  return (
    <div class="max-w-xs w-full space-y-3">
      <div class="flex gap-2 items-center">
        <span class="text-xs text-muted-foreground font-medium">Filter mode:</span>
        <Button
          size="sm"
          variant={strategy() === 'contains' ? 'solid' : 'outline'}
          onClick={() => setStrategy('contains')}
        >
          contains
        </Button>
        <Button
          size="sm"
          variant={strategy() === 'startsWith' ? 'solid' : 'outline'}
          onClick={() => setStrategy('startsWith')}
        >
          startsWith
        </Button>
      </div>

      <Combobox
        items={CITIES}
        filterMethod={strategy()}
        placeholder={`Search cities (${strategy()})...`}
        leading="i-lucide:search"
        openOnControlClick
      />
    </div>
  )
}

Search remote repositories#

Drive searchValue, onSearchValueChange, and loading from a debounced request. Set filterMethod={false} when the server already returns the matched items.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'
import { createSignal } from 'solid-js'

interface RepoItem extends ComboboxT.Item {
  label: string
}

const ALL_REPOS: RepoItem[] = [
  { label: 'subframe7536/moraine', value: 'moraine', icon: 'i-lucide:box' },
  { label: 'solidjs/solid', value: 'solid', icon: 'i-lucide:box' },
  { label: 'tailwindlabs/tailwindcss', value: 'tailwind', icon: 'i-lucide:box' },
  { label: 'unocss/unocss', value: 'unocss', icon: 'i-lucide:box' },
  { label: 'vitejs/vite', value: 'vite', icon: 'i-lucide:box' },
]

export function AsyncSearch() {
  const [query, setQuery] = createSignal('')
  const [loading, setLoading] = createSignal(false)
  const [items, setItems] = createSignal<ComboboxT.Item[]>(ALL_REPOS)

  let timer: ReturnType<typeof setTimeout> | undefined

  function handleSearch(search: string) {
    setQuery(search)
    setLoading(true)
    clearTimeout(timer)

    timer = setTimeout(() => {
      const filtered = ALL_REPOS.filter((item) =>
        item.label.toLowerCase().includes(search.toLowerCase()),
      )
      setItems(filtered)
      setLoading(false)
    }, 400)
  }

  return (
    <div class="max-w-xs w-full space-y-2">
      <Combobox
        items={items()}
        searchValue={query()}
        onSearchValueChange={handleSearch}
        loading={loading()}
        filterMethod={false}
        placeholder="Type to search repositories..."
        leading="i-lucide:search"
        openOnControlClick
        clearable
      />
      <p class="text-xs text-muted-foreground">
        {loading() ? 'Searching remote index...' : `${items().length} repositories found`}
      </p>
    </div>
  )
}

Browse grouped technologies#

Organize options into type: 'group' entries. Use emptyRender to customize the empty state when the query has no matches.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'

const TECH_GROUPS: ComboboxT.Entry[] = [
  {
    type: 'group',
    label: 'Frontend Frameworks',
    items: [
      { label: 'SolidJS', value: 'solid', icon: 'i-lucide:atom' },
      { label: 'Vue.js', value: 'vue', icon: 'i-lucide:sparkles' },
      { label: 'React', value: 'react', icon: 'i-lucide:box' },
      { label: 'Svelte', value: 'svelte', icon: 'i-lucide:flame' },
    ],
  },
  {
    type: 'group',
    label: 'Backend & Systems',
    items: [
      { label: 'Rust', value: 'rust', icon: 'i-lucide:cog' },
      { label: 'Go', value: 'go', icon: 'i-lucide:zap' },
      { label: 'Node.js', value: 'node', icon: 'i-lucide:server' },
    ],
  },
  {
    type: 'group',
    label: 'Databases',
    items: [
      { label: 'PostgreSQL', value: 'postgres', icon: 'i-lucide:database' },
      { label: 'Redis', value: 'redis', icon: 'i-lucide:database' },
      { label: 'SQLite', value: 'sqlite', icon: 'i-lucide:database' },
    ],
  },
]

export function Groups() {
  return (
    <div class="max-w-xs w-full space-y-2">
      <Combobox
        items={TECH_GROUPS}
        placeholder="Filter technologies..."
        leading="i-lucide:search"
        openOnControlClick
        emptyRender={(ctx) => (
          <div class="text-xs text-muted-foreground p-3 text-center">
            No technology found matching &ldquo;
            <span class="text-foreground font-medium">{ctx.searchValue}</span>&rdquo;.
          </div>
        )}
      />
    </div>
  )
}

Search a large collection#

Pass a createListVirtualizer instance as virtualizer when rendering every row on open is slow.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

const ITEMS: ComboboxT.Item<string>[] = Array.from({ length: 10_000 }, (_, index) => ({
  value: `option-${index}`,
  label: `Option ${index + 1}`,
}))

export function Virtualization() {
  const virtualizer = createListVirtualizer<ComboboxT.Row<ComboboxT.Item<string>>>({
    estimateSize: (entry) => (entry.type === 'label' ? 30 : 32),
    getItemKey: (entry) => entry.key,
    overscan: 8,
  })

  return (
    <div class="max-w-xs w-full">
      <Combobox
        items={ITEMS}
        placeholder="Search 10,000 options..."
        leading="i-lucide:search"
        openOnControlClick
        virtualizer={virtualizer}
        classes={{ listbox: 'h-80 max-h-80' }}
      />
    </div>
  )
}

Bind a searchable field to a form#

Use form.Field from createForm when the selected value needs schema validation and error display. required is satisfied by any selected item, including a disabled one. In that case the combobox passes constraint validation but submits no value, as a native <select> does with a disabled selected option.

import { Button, createForm, Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

const FRAMEWORKS = [
  { label: 'SolidJS', value: 'solid' },
  { label: 'Vue.js', value: 'vue' },
  { label: 'React', value: 'react' },
  { label: 'Svelte', value: 'svelte' },
  { label: 'Astro', value: 'astro' },
] satisfies ComboboxT.Item[]

export function FormIntegration() {
  const [submitted, setSubmitted] = createSignal<string | null>(null)
  const form = createForm({
    schema: v.object({
      framework: v.pipe(
        v.nullable(v.string()),
        v.check(
          (value): value is string => value !== null && value.length > 0,
          'Please select a primary framework.',
        ),
      ),
    }),
    initialInput: { framework: null },
    validate: 'input',
  })

  return (
    <form.Form onSubmit={(output) => setSubmitted(output.framework)}>
      <div class="max-w-xl space-y-4">
        <form.Field
          name="framework"
          label="Primary Framework"
          description="Used to configure your starter template and linting rules."
          required
        >
          <Combobox
            items={FRAMEWORKS}
            placeholder="Search and select framework..."
            leading="i-lucide:search"
            openOnControlClick
            clearable
          />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Validate
          </Button>
          <p class="text-xs text-muted-foreground">
            Selected:{' '}
            <span class="text-foreground font-medium font-mono">{submitted() ?? 'none'}</span>
          </p>
        </div>
      </div>
    </form.Form>
  )
}

Keep the query separate from the committed value#

value is the selected item. searchValue is the text in the field. Reset both when the page clears the picker.

import { Button, Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'
import { createSignal } from 'solid-js'

const FRAMEWORKS: ComboboxT.Item[] = [
  { label: 'SolidJS', value: 'solid' },
  { label: 'Vue.js', value: 'vue' },
  { label: 'React', value: 'react' },
  { label: 'Svelte', value: 'svelte' },
  { label: 'Astro', value: 'astro' },
]

export function UsageQuery() {
  const [selected, setSelected] = createSignal<string | undefined>('solid')
  const [query, setQuery] = createSignal('')

  return (
    <div class="max-w-xs w-full space-y-3">
      <Combobox
        items={FRAMEWORKS}
        value={selected()}
        onValueChange={setSelected}
        searchValue={query()}
        onSearchValueChange={setQuery}
        placeholder="Search framework..."
        leading="i-lucide:search"
        clearable
      />
      <div class="text-xs text-muted-foreground space-y-1">
        <p>
          Committed Value:{' '}
          <span class="text-foreground font-medium font-mono">{selected() ?? 'undefined'}</span>
        </p>
        <p>
          Query Text:{' '}
          <span class="text-foreground font-medium font-mono">
            {query() ? `"${query()}"` : '(idle)'}
          </span>
        </p>
      </div>
      <Button
        variant="ghost"
        size="sm"
        disabled={selected() === undefined && !query()}
        onClick={() => {
          setSelected(undefined)
          setQuery('')
        }}
      >
        Reset Both
      </Button>
    </div>
  )
}

Open the list from the whole field#

By default, typing and the chevron button open the popup. Set openOnControlClick when a click anywhere on the control should open it, as in an assignee picker.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'

const ITEMS: ComboboxT.Item[] = [
  { label: 'Development', value: 'dev' },
  { label: 'Design', value: 'design' },
  { label: 'Marketing', value: 'marketing' },
  { label: 'Product', value: 'product' },
]

export function ExplicitTrigger() {
  return (
    <div class="max-w-md w-full space-y-4">
      <div class="space-y-1.5">
        <label class="text-xs text-muted-foreground font-medium block">
          Default (Only typing or chevron button toggles popup)
        </label>
        <Combobox items={ITEMS} openOnControlClick={false} placeholder="Click chevron to open..." />
      </div>

      <div class="space-y-1.5">
        <label class="text-xs text-muted-foreground font-medium block">
          Open on control click (Click anywhere inside field to open)
        </label>
        <Combobox
          items={ITEMS}
          openOnControlClick={true}
          placeholder="Click anywhere in the field..."
        />
      </div>
    </div>
  )
}

Accept string labels or mixed items#

Pass a string array when the label is the value. Mix strings, item objects, and type: 'group' entries in one items list.

import { Combobox } from 'moraine'
import type { ComboboxT } from 'moraine'

const MIXED_STATUSES: ComboboxT.Entry[] = [
  'Open',
  { value: 'progress', label: 'In progress', description: 'Someone is actively working this' },
  {
    type: 'group',
    label: 'Closed',
    items: ['Done', { value: 'wontfix', label: "Won't fix", disabled: true }],
  },
]

export function StringItems() {
  return (
    <div class="flex flex-col gap-3 max-w-xs w-full">
      <Combobox
        aria-label="Issue status"
        items={['Open', 'In progress', 'Blocked', 'Done']}
        defaultValue="Open"
        clearable
      />
      <Combobox
        aria-label="Issue status with groups"
        items={MIXED_STATUSES}
        placeholder="Choose a status..."
        clearable
      />
    </div>
  )
}

API Reference#

Attributes#

Attributes
data-closed
Slot: combobox-controlcombobox-content
Description: Present when disclosure or transition content is closed.
data-disabled
Slot: combobox-controlcombobox-item
Description: Present when the component, slot, or item is disabled.
data-editable
Slot: combobox-control
Description: Present when the value can be edited as text.
data-expanded
Slot: combobox-controlcombobox-content
Description: Present when the panel, accordion, or menu is expanded.
data-invalid
Slot: combobox-control
Description: Present when the field or form has a validation error.
data-readonly
Slot: combobox-control
Description: Present when the field is in read-only mode.
data-required
Slot: combobox-control
Description: Present when the field input is required.
data-side
Slot: combobox-content
Description: Stores the resolved floating or drawer content side.
data-highlighted
Slot: combobox-itemcombobox-item-description
Description: Present when the item is highlighted by pointer or keyboard navigation.
data-selected
Slot: combobox-item
Description: Present when the item or tab is selected.
data-loading
Slot: combobox-trigger
Description: Present when the component or async operation is loading.

Props#

Renders a <div> element by default.

Prop