[ 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.
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".
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.
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.
1/3 selected
Close after each pick#
closeOnSelect defaults to true for single and false for multiple. Override it either way.
<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.
Options: bug, feature, docs
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`}
/>[ Async search ]
For server-side search: disable built-in filtering, fetch on onInputChange, and pass loading while the request is in flight. Selected values keep their labels even after the results change.
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
[ 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.
Sizes#
sm, md (default) and lg match the Input, Select and Button sizes.
<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
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.
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().
API reference#
<Combobox />
Forwards its ref to the <input>. Other props (autoFocus, readOnly, aria-*, data-*, onBlur, onFocus, onKeyDown…) go on the <input>.
| Prop | Type | Default | Description |
|---|---|---|---|
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). |
multiple | boolean | false | 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. |
filter | ((option, query) => boolean) | false | comboboxFilter | Decides which options match. false shows options as-is (server-side filtering). |
limit | number | - | Maximum number of matching options rendered. |
highlightMatches | boolean | true | Bold the matched part of string labels. |
renderOption | (option, { active, selected, query }) => ReactNode | - | Custom content for each option row. |
creatable | boolean | false | 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 | (text) => ReactNode | (t) => `Create "${t}"` | Content of the create row. |
loading | boolean | false | Shows a spinner in the field and a loading row in the list. |
loadingText | ReactNode | 'Loading…' | Text of the loading row. |
emptyText | ReactNode | (query) => ReactNode | 'No results' | Shown when nothing matches. |
clearable | boolean | true | Show the × button; emptying the text and leaving clears the value. |
closeOnSelect | boolean | !multiple | Close the list after an option is picked. |
openOnFocus | boolean | false | Open the list when the input receives focus. |
leftIcon | ReactNode | - | Icon rendered inside the field, before the text. |
size | 'sm' | 'md' | 'lg' | 'md' | 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. |
fullWidth | boolean | false | Makes the field fill its container. |
containerClassName | string | - | Class for the outer wrapper. className goes on the <input>. |
required | boolean | false | Blocks native form submit until a value is chosen, plus a red asterisk. |
disabled | boolean | false | Disables and dims the field. |
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) => voidCalled with the new value and its option (arrays of both when multiple; null when cleared).
multiplefalsebooleanPick many values, shown as removable tags.
placeholder-stringShown while the input is empty (hidden once tags exist).
inputValue-stringTyped text (controlled).
defaultInputValue-stringInitial typed text (uncontrolled). Defaults to the selected label.
onInputChange-(text, reason: 'input' | 'select' | 'clear' | 'reset') => voidCalled whenever the text changes. Fetch on reason === "input" for async search.
onOpenChange-(open: boolean) => voidCalled when the list opens or closes.
filtercomboboxFilter((option, query) => boolean) | falseDecides which options match. false shows options as-is (server-side filtering).
limit-numberMaximum number of matching options rendered.
highlightMatchestruebooleanBold the matched part of string labels.
renderOption-(option, { active, selected, query }) => ReactNodeCustom content for each option row.
creatablefalsebooleanOffer a "Create …" row when the text matches no option.
onCreate-(text) => ComboboxOption | value | voidCalled when the create row is chosen. Return the new option (or its value); otherwise the text is used.
formatCreateLabel(t) => `Create "${t}"`(text) => ReactNodeContent of the create row.
loadingfalsebooleanShows a spinner in the field and a loading row in the list.
loadingText'Loading…'ReactNodeText of the loading row.
emptyText'No results'ReactNode | (query) => ReactNodeShown when nothing matches.
clearabletruebooleanShow the × button; emptying the text and leaving clears the value.
closeOnSelect!multiplebooleanClose the list after an option is picked.
openOnFocusfalsebooleanOpen the list when the input receives focus.
leftIcon-ReactNodeIcon rendered inside the field, before the text.
size'md''sm' | 'md' | 'lg'Field height and font size.
name-stringSubmits the value with forms via hidden inputs (one per value when multiple).
label-ReactNodeLabel rendered above the field and linked to the input via htmlFor.
helperText-ReactNodeHint shown below the field.
error-boolean | stringMarks the field invalid (red border, aria-invalid). A string also replaces the helper text.
fullWidthfalsebooleanMakes the field fill its container.
containerClassName-stringClass for the outer wrapper. className goes on the <input>.
requiredfalsebooleanBlocks native form submit until a value is chosen, plus a red asterisk.
disabledfalsebooleanDisables and dims the field.
<ComboboxOption />
The shape of each option. Any extra fields are kept and passed to renderOption and onChange.
| Prop | Type | Default | Description |
|---|---|---|---|
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. |
label*-ReactNodeOption text. String labels are searched and highlighted.
value*-string | numberUnique value.
description-ReactNodeSecondary line under the label.
icon-ReactNodeIcon before the label (also shown on tags).
keywords-string[]Extra search terms that are not displayed.
textValue-stringPlain text for the input and search when label is not a string.
disabled-booleanOption 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.
| Prop | Type | Default | Description |
|---|---|---|---|
option* | ComboboxOption | - | The option being tested. |
query* | string | - | Typed text. Matches label or keywords, case-insensitive "contains". |
option*-ComboboxOptionThe option being tested.
query*-stringTyped 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.