[ Forms ]

Combobox

A text input with a filterable dropdown list, also called an autocomplete. Users type to narrow the options and pick one value, or several with multiple. It supports groups, icons, keyword search, creating new options, async server search with loading states, custom option rendering and native form submission.

25 examplesDark modeAccessible

Import#

import { Combobox } from 'reusify-ui';

When to use#

  • Picking from a long list (roughly 15+ options) where scrolling would be slow: countries, people, products, timezones.
  • When users already know what they are looking for and typing is faster than browsing.
  • Tag-style inputs that pick many values (multiple), optionally letting users add new ones (creatable).
  • Searching a server-side dataset that is too big to load at once (filter={false} + loading + onInputChange).
  • For short lists (under ~15 items) a Select is simpler; for 2 to 4 options use a RadioGroup.

Examples#

[ Basics ]

Pass options as { label, value } objects, the same shape Select uses, so switching between them is a one-word change.

Basic#

Click the field or start typing to filter. Matching text is bolded. Use Arrow keys and Enter to pick. Disabled options (Ember) stay visible but cannot be chosen.

const frameworks = [
  { label: 'React', value: 'react' },
  { label: 'Vue', value: 'vue' },
  { label: 'Angular', value: 'angular' },
  { label: 'Svelte', value: 'svelte' },
  { label: 'Solid', value: 'solid' },
  { label: 'Preact', value: 'preact' },
  { label: 'Qwik', value: 'qwik' },
  { label: 'Ember', value: 'ember', disabled: true },
];

<Combobox label="Framework" placeholder="Search frameworks…" options={frameworks} />

Default value#

Uncontrolled: defaultValue sets the starting value and the input shows its label. Open it again and you'll see the full list with the current option highlighted. Delete the text and blur to clear the value.

<Combobox label="Framework" defaultValue="vue" options={frameworks} />

Controlled#

Pass value and onChange. onChange receives the new value directly (not an event), plus the full option object as a second argument. Set the value to null to clear it.

Value: "svelte"

const [framework, setFramework] = useState('svelte');

<Combobox
  label="Framework"
  options={frameworks}
  value={framework}
  onChange={setFramework}   // (value, option) => void
/>

<Button onClick={() => setFramework('react')}>Set React</Button>
<Button onClick={() => setFramework(null)}>Reset</Button>

Icons & descriptions#

Options can carry an icon and a secondary description line, exactly like Select.

import { FiLayers, FiServer, FiDatabase, FiSmartphone, FiCode } from 'react-icons/fi';

const stacks = [
  { label: 'Frontend', value: 'frontend', description: 'React, CSS, accessibility', icon: <FiLayers /> },
  { label: 'Backend', value: 'backend', description: 'APIs, queues, auth', icon: <FiServer /> },
  { label: 'Database', value: 'database', description: 'Postgres, Redis, indexing', icon: <FiDatabase /> },
  { label: 'Mobile', value: 'mobile', description: 'React Native, iOS, Android', icon: <FiSmartphone /> },
  { label: 'DevOps', value: 'devops', description: 'CI/CD, Docker, cloud', icon: <FiCode /> },
];

<Combobox label="Team" placeholder="Search teams…" options={stacks} />

Groups#

Nest options one level deep with { label, options: [...] }. Groups with no matches are hidden while filtering. Try typing "pa".

const cuisines = [
  {
    label: 'Indian',
    options: [
      { label: 'Biryani', value: 'biryani' },
      { label: 'Masala Dosa', value: 'dosa' },
      { label: 'Paneer Tikka', value: 'paneer-tikka' },
    ],
  },
  {
    label: 'Italian',
    options: [
      { label: 'Margherita Pizza', value: 'pizza' },
      { label: 'Pasta Carbonara', value: 'carbonara' },
    ],
  },
];

<Combobox label="Dish" leftIcon={<FiCoffee />} options={cuisines} />

Empty state#

emptyText is shown when nothing matches. It can be a function of the typed text. Try typing "xyz".

<Combobox
  label="Framework"
  options={frameworks}
  emptyText={(query) => `No framework called "${query}"`}
/>

[ Multiple selection ]

With multiple, the value is an array and chosen options appear as removable tags inside the field. The list stays open so users can pick several in a row.

Tags#

Click an option again to deselect it, click × on a tag, or press Backspace in the empty input to remove the last tag.

ReactTypeScript

Value: ["react","typescript"]

const [value, setValue] = useState(['react', 'typescript']);

<Combobox
  label="Skills"
  multiple
  options={skills}
  value={value}
  onChange={setValue}      // receives string[]
  placeholder="Add skills…"
/>

Limit the number of picks#

There is no special prop: derive the options from the value and disable the unpicked ones once the limit is reached.

React

1/3 selected

const max = 3;
const [value, setValue] = useState(['react']);
const full = value.length >= max;

const options = useMemo(
  () => skills.map((o) => ({ ...o, disabled: full && !value.includes(o.value) })),
  [full, value],
);

<Combobox
  label="Top skills"
  multiple
  options={options}
  value={value}
  onChange={setValue}
  helperText={`${value.length}/${max} selected`}
/>

Close after each pick#

closeOnSelect defaults to true for single and false for multiple. Override it either way.

Figma
<Combobox label="Skills" multiple closeOnSelect options={skills} defaultValue={['figma']} />

[ Filtering ]

By default options match when their label contains the typed text (case-insensitive). Add keywords, swap in your own filter, or turn filtering off.

Search by keywords#

keywords are extra search terms that are not displayed. Try "UK", "Dubai", "Bharat" or "Tokyo".

const countries = [
  { label: 'India', value: 'IN', keywords: ['IN', 'Bharat', 'New Delhi'] },
  { label: 'United Kingdom', value: 'GB', keywords: ['UK', 'GB', 'Britain', 'London'] },
  { label: 'United Arab Emirates', value: 'AE', keywords: ['UAE', 'Dubai', 'Abu Dhabi'] },
  { label: 'Japan', value: 'JP', keywords: ['JP', 'Nippon', 'Tokyo'] },
  // …
];

<Combobox label="Country" leftIcon={<FiGlobe />} options={countries} />

Custom filter#

filter receives (option, query) and returns true to keep the option. This one only matches the start of the label: "re" finds React but not Preact.

const startsWith = (option, query) =>
  option.label.toLowerCase().startsWith(query.trim().toLowerCase());

<Combobox label="Framework" options={frameworks} filter={startsWith} />

// Extend the default instead of replacing it:
import { comboboxFilter } from 'reusify-ui';
const filter = (option, query) => comboboxFilter(option, query) || option.value === query;

Large lists#

limit caps how many matching options are rendered, so even thousands of options stay fast. This list has 2,000 products, showing the first 50 matches. Try "monitor 01".

Showing up to 50 matches

const products = Array.from({ length: 2000 }, (_, i) => ({
  label: `Product SKU-${i + 1}`,
  value: `sku-${i + 1}`,
}));

<Combobox label="Product" options={products} limit={50} />

Without match highlighting#

highlightMatches={false} turns off bolding the matched part of each label.

<Combobox label="Framework" options={frameworks} highlightMatches={false} />

[ Creating options ]

creatable adds a "Create …" row when the typed text does not exactly match any option. onCreate(text) lets you save it and return the new option.

Creatable tags#

Type "Performance" and press Enter. onCreate adds it to options and returns the option; its value is then selected. If onCreate returns nothing, the trimmed text itself becomes the value.

Bug

Options: bug, feature, docs

const [options, setOptions] = useState([
  { label: 'Bug', value: 'bug' },
  { label: 'Feature', value: 'feature' },
  { label: 'Docs', value: 'docs' },
]);
const [labels, setLabels] = useState(['bug']);

<Combobox
  label="Issue labels"
  multiple
  creatable
  options={options}
  value={labels}
  onChange={setLabels}
  onCreate={(text) => {
    const option = { label: text, value: slugify(text), icon: <FiTag /> };
    setOptions((prev) => [...prev, option]);
    return option; // or return just a value, or nothing
  }}
/>

Single value & custom create label#

creatable also works for a single value. formatCreateLabel changes the text of the create row.

<Combobox
  label="Company"
  creatable
  options={companies}
  formatCreateLabel={(text) => `Add "${text}" as a new company`}
/>

Search an API#

Try "re" or "vite". Results are debounced by 300ms and the field shows a spinner while loading. Only typing and clearing trigger a fetch (reason "input" / "clear"), not the text being reset after a pick.

Selected: null

function RepoSearch() {
  const [query, setQuery] = useState('');
  const [options, setOptions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [repo, setRepo] = useState(null);

  useEffect(() => {
    if (!query.trim()) return setOptions([]);
    let cancelled = false;
    setLoading(true);
    const timer = setTimeout(async () => {
      const results = await api.searchRepos(query); // [{ label, value, description }]
      if (!cancelled) {
        setOptions(results);
        setLoading(false);
      }
    }, 300);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [query]);

  return (
    <Combobox
      label="Repository"
      leftIcon={<FiSearch />}
      options={options}
      filter={false}             // the server already filtered
      loading={loading}
      loadingText="Searching…"
      emptyText={(q) => (q ? `No repositories match "${q}"` : 'Start typing to search')}
      value={repo}
      onChange={setRepo}
      // Fetch on typing and clearing, not when the text is reset after a pick or blur.
      onInputChange={(text, reason) => (reason === 'input' || reason === 'clear') && setQuery(text)}
    />
  );
}

[ Customization ]

Change how options look, how the field looks, and how it behaves when focused.

Custom option rendering#

renderOption(option, { active, selected, query }) replaces the default row content. Extra fields on your options (email, role) are passed through. The ru-select__text / __label / __desc classes give you the built-in typography.

const people = [
  { label: 'Aarav Sharma', value: 'aarav', email: 'aarav@acme.dev', role: 'Admin', keywords: ['aarav@acme.dev'] },
  { label: 'Priya Verma', value: 'priya', email: 'priya@acme.dev', role: 'Editor', keywords: ['priya@acme.dev'] },
  // …
];

<Combobox
  label="Assignee"
  options={people}
  placeholder="Search by name or email"
  renderOption={(person) => (
    <>
      <Avatar name={person.label} size="sm" />
      <span className="ru-select__text">
        <span className="ru-select__label">{person.label}</span>
        <span className="ru-select__desc">{person.email}</span>
      </span>
      <Badge size="sm" variant="soft" color={roleColor[person.role]}>{person.role}</Badge>
    </>
  )}
/>

Sizes#

sm, md (default) and lg match the Input, Select and Button sizes.

ReactAWS
ReactAWS
ReactAWS
<Combobox size="sm" options={frameworks} placeholder="Small" />
<Combobox size="md" options={frameworks} placeholder="Medium" />
<Combobox size="lg" options={frameworks} placeholder="Large" />
<Combobox size="sm" multiple options={skills} defaultValue={['react', 'aws']} />

Error, disabled, read-only & required#

Please choose a framework

React

Required field

<Combobox label="Framework" options={frameworks} error="Please choose a framework" />
<Combobox label="Framework" options={frameworks} defaultValue="react" disabled />
<Combobox label="Skills" multiple options={skills} defaultValue={['react']} readOnly />
<Combobox label="Framework" options={frameworks} required helperText="Required field" />

Open on focus & no clear button#

openOnFocus opens the list as soon as the field is focused (including via Tab). clearable={false} hides the × button and keeps the value when the text is emptied.

<Combobox label="Framework" options={frameworks} openOnFocus />
<Combobox label="Framework" options={frameworks} defaultValue="react" clearable={false} />

[ Forms & state ]

Combobox submits with native forms, exposes its typed text, and plays well with form libraries.

Native forms#

With name, the value is submitted through hidden inputs; multiple submits one entry per value, so read it with FormData.getAll(). required blocks submit until something is chosen: try submitting empty.

<form onSubmit={(e) => {
  e.preventDefault();
  const data = new FormData(e.currentTarget);
  console.log(data.get('stack'));     // 'frontend'
  console.log(data.getAll('skills')); // ['react', 'aws']
}}>
  <Combobox label="Primary stack" name="stack" required options={stacks} />
  <Combobox label="Skills" name="skills" multiple options={skills} />
  <Button type="submit">Save profile</Button>
</form>

Controlled input text#

inputValue / onInputChange control the typed text separately from the value. reason tells you why it changed: "input" (typing), "select" (an option was picked), "clear" (× button) or "reset" (synced back to the value on blur, Escape or a value change).

Events appear here.

const [text, setText] = useState('');

<Combobox
  label="City"
  options={cities}
  inputValue={text}
  onInputChange={(next, reason) => setText(next)}
/>

<Button onClick={() => setText('Pu')}>Type "Pu"</Button>

Dependent fields#

Reset the child value when the parent changes, so a city from another country never stays selected.

const [country, setCountry] = useState('IN');
const [city, setCity] = useState(null);

<Combobox
  label="Country"
  options={countries}
  value={country}
  onChange={(next) => {
    setCountry(next);
    setCity(null);
  }}
/>
<Combobox
  label="City"
  options={(citiesByCountry[country] ?? []).map((c) => ({ label: c, value: c }))}
  value={city}
  onChange={setCity}
  disabled={!country}
/>

Events & ref#

onChange gets (value, option). onOpenChange fires when the list opens or closes. The ref points at the <input>, so focus() and select() work. Native input props (onBlur, onFocus, autoFocus, aria-*, data-*) are passed to it too.

Interact to see events.

const inputRef = useRef(null);

<Combobox
  ref={inputRef}
  label="Framework"
  options={frameworks}
  onChange={(value, option) => console.log(value, option?.label)}
  onOpenChange={(open) => console.log('open', open)}
/>

<Button onClick={() => inputRef.current.focus()}>Focus via ref</Button>

With React Hook Form#

Combobox's onChange gives a value instead of an event, so wire it with Controller (or useController) rather than register().

Pick a country

React
import { Controller, useForm } from 'react-hook-form';

function ProfileForm() {
  const { control, handleSubmit } = useForm({ defaultValues: { country: null, skills: [] } });

  return (
    <form onSubmit={handleSubmit(console.log)}>
      <Controller
        name="country"
        control={control}
        rules={{ required: 'Pick a country' }}
        render={({ field, fieldState }) => (
          <Combobox
            label="Country"
            options={countries}
            value={field.value}
            onChange={field.onChange}
            onBlur={field.onBlur}
            ref={field.ref}
            error={fieldState.error?.message}
          />
        )}
      />
      <Controller
        name="skills"
        control={control}
        render={({ field }) => (
          <Combobox label="Skills" multiple options={skills} value={field.value} onChange={field.onChange} />
        )}
      />
      <Button type="submit">Save</Button>
    </form>
  );
}

API reference#

<Combobox />

Forwards its ref to the <input>. Other props (autoFocus, readOnly, aria-*, data-*, onBlur, onFocus, onKeyDown…) go on the <input>.

options[]
ComboboxOption[] | { label, options: ComboboxOption[] }[]

Options, optionally grouped one level deep.

value-
string | number | null (array when multiple)

Selected value (controlled).

defaultValue-
string | number (array when multiple)

Initially selected value (uncontrolled).

onChange-
(value, option) => void

Called with the new value and its option (arrays of both when multiple; null when cleared).

multiplefalse
boolean

Pick many values, shown as removable tags.

placeholder-
string

Shown while the input is empty (hidden once tags exist).

inputValue-
string

Typed text (controlled).

defaultInputValue-
string

Initial typed text (uncontrolled). Defaults to the selected label.

onInputChange-
(text, reason: 'input' | 'select' | 'clear' | 'reset') => void

Called whenever the text changes. Fetch on reason === "input" for async search.

onOpenChange-
(open: boolean) => void

Called when the list opens or closes.

filtercomboboxFilter
((option, query) => boolean) | false

Decides which options match. false shows options as-is (server-side filtering).

limit-
number

Maximum number of matching options rendered.

highlightMatchestrue
boolean

Bold the matched part of string labels.

renderOption-
(option, { active, selected, query }) => ReactNode

Custom content for each option row.

creatablefalse
boolean

Offer a "Create …" row when the text matches no option.

onCreate-
(text) => ComboboxOption | value | void

Called when the create row is chosen. Return the new option (or its value); otherwise the text is used.

formatCreateLabel(t) => `Create "${t}"`
(text) => ReactNode

Content of the create row.

loadingfalse
boolean

Shows a spinner in the field and a loading row in the list.

loadingText'Loading…'
ReactNode

Text of the loading row.

emptyText'No results'
ReactNode | (query) => ReactNode

Shown when nothing matches.

clearabletrue
boolean

Show the × button; emptying the text and leaving clears the value.

closeOnSelect!multiple
boolean

Close the list after an option is picked.

openOnFocusfalse
boolean

Open the list when the input receives focus.

leftIcon-
ReactNode

Icon rendered inside the field, before the text.

size'md'
'sm' | 'md' | 'lg'

Field height and font size.

name-
string

Submits the value with forms via hidden inputs (one per value when multiple).

label-
ReactNode

Label rendered above the field and linked to the input via htmlFor.

helperText-
ReactNode

Hint shown below the field.

error-
boolean | string

Marks the field invalid (red border, aria-invalid). A string also replaces the helper text.

fullWidthfalse
boolean

Makes the field fill its container.

containerClassName-
string

Class for the outer wrapper. className goes on the <input>.

requiredfalse
boolean

Blocks native form submit until a value is chosen, plus a red asterisk.

disabledfalse
boolean

Disables and dims the field.

<ComboboxOption />

The shape of each option. Any extra fields are kept and passed to renderOption and onChange.

label*-
ReactNode

Option text. String labels are searched and highlighted.

value*-
string | number

Unique value.

description-
ReactNode

Secondary line under the label.

icon-
ReactNode

Icon before the label (also shown on tags).

keywords-
string[]

Extra search terms that are not displayed.

textValue-
string

Plain text for the input and search when label is not a string.

disabled-
boolean

Option can't be chosen and is skipped by the keyboard.

comboboxFilter(option, query)

The default filter, exported so custom filters can build on it. getOptionText(option) is exported as well.

option*-
ComboboxOption

The option being tested.

query*-
string

Typed text. Matches label or keywords, case-insensitive "contains".

Accessibility#

  • Implements the WAI-ARIA editable combobox with list autocomplete: the <input> has role="combobox", aria-autocomplete="list", aria-expanded and aria-controls pointing to a role="listbox". Focus stays in the input; the highlighted option is exposed with aria-activedescendant.
  • Arrow Down / Arrow Up open the list (on the first / last option) and move the highlight; Enter picks; Escape closes the list, and a second Escape restores the text. Enter submits the form when no option is highlighted.
  • Typing filters immediately and highlights the first match, so typing and pressing Enter picks it.
  • With multiple, the listbox has aria-multiselectable, Backspace in an empty input removes the last tag, and each tag's remove button has an accessible name ("Remove React").
  • The clear, toggle and tag-remove buttons are skipped by Tab (tabIndex -1) since the keyboard already covers them, keeping one tab stop per field.
  • The label, helper text and error are linked to the input; required uses native form validation.
  • Pressing Escape inside a Modal or Drawer closes only the list, not the dialog. While loading, the list has aria-busy and the spinner announces its loading text.