@k8ordo/ui

Combobox

A field for picking one option. Typing filters the options, or search asks a server for them.

Import

ts
import { Combobox } from '@k8ordo/ui';

Usage

Typing opens the list. The value changes only when an option is picked with a click or Enter. Blurring in the middle of typing puts the chosen label back. Blurring an empty field clears the choice. ↓ and ↑ open the list and move through it; Alt+↓ only opens it. Escape closes it, and pressed again drops what was typed. To pick several, use Autocomplete.

tsx
<Combobox aria-label="Prefecture" name="prefecture" options={prefectures} />

Searching a server

With search, each keystroke calls it for the options. Typing again aborts the previous call’s signal, so pass it on to fetch. While a search runs, the list has aria-busy. A failure and an empty result are shown in the list and announced. options becomes what is shown before anything is typed.

tsx
<Combobox
  aria-label="City"
  name="city"
  search={async (query, { signal }) => {
    const response = await fetch(
      `/api/cities?q=${encodeURIComponent(query)}`,
      { signal },
    );
    return response.json();
  }}
/>

With @k8ordo/form

Spread the input derived from z.enum() as it is. The choice submits through a hidden <select>, so required and the rules apply to it. A form’s reset, and moving focus after a failed submission, work too.

tsx
// schema.ts
export const addressSchema = z.object({
  prefecture: z.enum(['hokkaido', 'tokyo', 'osaka']),
});

// address-form.tsx
const prefecture = form.field('prefecture');

<FormControl
  errorText={prefecture.error}
  invalid={prefecture.invalid}
  label="Prefecture"
  required={prefecture.required}
  renderInput={(props) => (
    <Combobox {...props} {...prefecture.input} options={prefectures} />
  )}
/>

Props

defaultValue?
Type: string
Default: -
invalid?
Type: boolean
Default: false
onChange?
Type: (value: string) => void
Default: -
options?
Type: readonly Option[]
Default: -
ref?
Type: Ref<HTMLInputElement>
Default: -
search?
Type: ComboboxSearch
Default: -
type?
Type: string
Default: -
value?
Type: string
Default: -
PropTypeDefault
defaultValue?string-
invalid?booleanfalse
onChange?(value: string) => void-
options?readonly Option[]-
ref?Ref<HTMLInputElement>-
search?ComboboxSearch-
type?string-
value?string-

Inherited attributes (except the ones set internally): InputHTMLAttributes<HTMLInputElement>

The wording this component draws (labels, placeholders, and so on) comes from the message dictionary unless a prop sets it. To replace it, see: i18n

k8ordo

React libraries that use Baseline features without holding back.