Combobox

Combobox is a composable component which allows users to filter a list of items. It includes an input field that acts as a trigger, a popover which display the list of items.

Quick Start

Installation
npm install @adaptavant/eds-core
Import
import { Combobox } from '@adaptavant/eds-core';

Open Menu

By default, the menu opens when the user types in the trigger input. Also, using menuTrigger="focus" prop allows you to open the menu when the input is focused.

const initialOptions = [
	{ id: '1', value: 'Item 1' },
	{ id: '2', value: 'Item 2' },
	{ id: '3', value: 'Item 3' },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState('');
const filteredOptions = React.useMemo(() => {
	if (searchTerm === '') return initialOptions;
	return initialOptions.filter((item) =>
		item.value.toLowerCase().includes(searchTerm.toLowerCase())
	);
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
	setSelectedOption(selectedOption);
	setSearchTerm('');
};

return (
	<Field label="Select Items">
		<Combobox
			inputValue={searchTerm || selectedOption?.value}
			menuTrigger="focus"
			onClear={() => setSearchTerm('')}
			onClose={() => setSearchTerm('')}
			onInputChange={setSearchTerm}
			onSelectionChange={clearAndSelect}
			options={filteredOptions}
			selectedKey="value"
			selectedOption={selectedOption}
		>
			<ComboboxSearchInput placeholder="Search..." />
			<ComboboxPopover>
				<ComboboxListbox
					noResultsFallback={
						<Text className="text-secondary text-center text-body-12 py-4">
							No matching results
						</Text>
					}
					options={filteredOptions}
				>
					{(item) => <ComboboxItem option={item}>{item.value}</ComboboxItem>}
				</ComboboxListbox>
			</ComboboxPopover>
		</Combobox>
	</Field>
);

Composing Trigger

Trigger as Search Input

const initialOptions = [
	{ id: '1', value: 'Item 1' },
	{ id: '2', value: 'Item 2' },
	{ id: '3', value: 'Item 3' },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState('');
const filteredOptions = React.useMemo(() => {
	if (searchTerm === '') return initialOptions;
	return initialOptions.filter((item) =>
		item.value.toLowerCase().includes(searchTerm.toLowerCase())
	);
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
	setSelectedOption(selectedOption);
	setSearchTerm('');
};

return (
	<Field label="Select Items">
		<Combobox
			inputValue={searchTerm || selectedOption?.value}
			onClear={() => setSearchTerm('')}
			onClose={() => setSearchTerm('')}
			onInputChange={setSearchTerm}
			onSelectionChange={clearAndSelect}
			options={filteredOptions}
			selectedKey="value"
			selectedOption={selectedOption}
		>
			<ComboboxSearchInput placeholder="Search..." />
			<ComboboxPopover>
				<ComboboxListbox
					noResultsFallback={
						<Text className="text-secondary text-center text-body-12 py-4">
							No matching results
						</Text>
					}
					options={filteredOptions}
				>
					{(item) => <ComboboxItem option={item}>{item.value}</ComboboxItem>}
				</ComboboxListbox>
			</ComboboxPopover>
		</Combobox>
	</Field>
);

Trigger as Text Input

const initialOptions = [
	{ id: '1', value: 'Item 1' },
	{ id: '2', value: 'Item 2' },
	{ id: '3', value: 'Item 3' },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState('');
const filteredOptions = React.useMemo(() => {
	if (searchTerm === '') return initialOptions;
	return initialOptions.filter((item) =>
		item.value.toLowerCase().includes(searchTerm.toLowerCase())
	);
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
	setSelectedOption(selectedOption);
	setSearchTerm('');
};

return (
	<Field label="Select Items">
		<Combobox
			inputValue={searchTerm || selectedOption?.value}
			onClear={() => setSearchTerm('')}
			onClose={() => setSearchTerm('')}
			onInputChange={setSearchTerm}
			onSelectionChange={clearAndSelect}
			options={filteredOptions}
			selectedKey="value"
			selectedOption={selectedOption}
		>
			<ComboboxTextInput placeholder="Search..." />
			<ComboboxPopover>
				<ComboboxListbox
					noResultsFallback={
						<Text className="text-secondary text-center text-body-12 py-4">
							No matching results
						</Text>
					}
					options={filteredOptions}
				>
					{(item) => <ComboboxItem option={item}>{item.value}</ComboboxItem>}
				</ComboboxListbox>
			</ComboboxPopover>
		</Combobox>
	</Field>
);

Also, if you wanted to have a custom clear.

const initialOptions = [
	{ id: '1', value: 'Item 1' },
	{ id: '2', value: 'Item 2' },
	{ id: '3', value: 'Item 3' },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState('');
const filteredOptions = React.useMemo(() => {
	if (searchTerm === '') return initialOptions;
	return initialOptions.filter((item) =>
		item.value.toLowerCase().includes(searchTerm.toLowerCase())
	);
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
	setSelectedOption(selectedOption);
	setSearchTerm('');
};

return (
	<Field label="Select Items">
		<Combobox
			inputValue={searchTerm || selectedOption?.value}
			onClear={() => setSearchTerm('')}
			onClose={() => setSearchTerm('')}
			onInputChange={setSearchTerm}
			onSelectionChange={clearAndSelect}
			options={filteredOptions}
			selectedKey="value"
			selectedOption={selectedOption}
		>
			<ComboboxTextInput
				adornmentEnd={
					searchTerm && (
						<ClickableAdornment
							className="text-primary leading-none"
							onClick={() => {
								setSearchTerm('');
								setSelectedOption(undefined);
							}}
						>
							<RemoveIcon size="16" />
						</ClickableAdornment>
					)
				}
				classNames={{
					adornmentEnd: 'pe-2',
				}}
				placeholder="Search..."
			/>
			<ComboboxPopover>
				<ComboboxListbox
					noResultsFallback={
						<Text className="text-secondary text-center text-body-12 py-4">
							No matching results
						</Text>
					}
					options={filteredOptions}
				>
					{(item) => <ComboboxItem option={item}>{item.value}</ComboboxItem>}
				</ComboboxListbox>
			</ComboboxPopover>
		</Combobox>
	</Field>
);

Popover Customizations

The Combobox component provides several props to customise the appearance and behavior of its popover. These props allow for fine-grained control over the popover’s width, height, offset, and placement relative to the trigger element.

  • popoverMatchReferenceWidth: Set to true to make the popover’s width match the trigger’s width, or false for independent width.
  • popoverMaxHeight: Sets the maximum height of the popover in pixels. The default is 356.
  • popoverMaxWidth: Sets the maximum width of the popover in pixels. The default is 400.
  • popoverOffset: Adjusts the space between the popover and the trigger, specified in pixels. The default is 4.
  • popoverPlacement: Determines the position of the popover relative to the trigger. Options include 'bottom', 'bottom-start', and 'bottom-end', allowing for flexible positioning based on the layout and space available. The default is 'bottom-start'. If there isn’t enough space for the popover to appear below the trigger, it will automatically switch to the top position.

For example:

<Combobox
	popoverMatchReferenceWidth={}
	popoverMaxHeight={}
	popoverMaxWidth={}
	popoverOffset={}
	popoverPlacement={}
	{...props}
>
	...
</Combobox>

Strategy

Use the strategy prop to change the way how popover element will be positioned. By default, the strategy is set to absolute, changes it to fixed when the ComboboxTrigger is inside a sticky or fixed element.

This option leverages the floating-ui library, which powers the ComboboxPopover functionality.

const initialOptions = [
	{ id: '1', value: 'Item 1' },
	{ id: '2', value: 'Item 2' },
	{ id: '3', value: 'Item 3' },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState('');

const [showFixedElement, setShowFixedElement] = React.useState(false);

const onButtonClick = () => {
	setShowFixedElement((prevState) => !prevState)
}

const filteredOptions = React.useMemo(() => {
	if (searchTerm === '') return initialOptions;
	return initialOptions.filter((item) =>
		item.value.toLowerCase().includes(searchTerm.toLowerCase())
	);
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
	setSelectedOption(selectedOption);
	setSearchTerm('');
};



return (
	<Stack className="w-full gap-4">
		{showFixedElement ? (
			<div className="
				animate-[snackbar-transition_0.3s_cubic-bezier(0.16,_1,_0.3,_1)]
				bg-neutral-secondary
				fixed
				flex
				items-center
				justify-between
				mx-2
				p-4
				right-0
				rounded-8px
				shadow-40
				sm:right-8
				sm:w-[360px]
				top-8
				w-[calc(100%-16px)]
				z-10
			">
				<Field label="Select Items">
					<Combobox
						inputValue={searchTerm || selectedOption?.value}
						menuTrigger="focus"
						onClear={() => setSearchTerm('')}
						onClose={() => setSearchTerm('')}
						onInputChange={setSearchTerm}
						onSelectionChange={clearAndSelect}
						options={filteredOptions}
						selectedKey="value"
						selectedOption={selectedOption}
						strategy="fixed"
					>
						<ComboboxSearchInput placeholder="Search..." />
						<ComboboxPopover>
							<ComboboxListbox
								noResultsFallback={
									<Text className="text-secondary text-center text-body-12 py-4">
										No matching results
									</Text>
								}
								options={filteredOptions}
							>
								{(item) => <ComboboxItem option={item}>{item.value}</ComboboxItem>}
							</ComboboxListbox>
						</ComboboxPopover>
					</Combobox>
				</Field>
				<button
					className="
						focus-visible:focus-ring
						font-stronger
						px-1
						py-0.5
						rounded-4px
						text-body-12
						text-primary
						underline
						underline-offset-2
					"
					onClick={onButtonClick}
				>
					Close
				</button>
			</div>
		) : null}
		<Button onClick={onButtonClick}>
			Show fixed element
		</Button>
	</Stack>
);

Disabled

Utilize the isDisabled prop in the <Field/> to show that a entire Combobox isn't usable.

const initialOptions = [
	{ id: '1', value: 'Item 1' },
	{ id: '2', value: 'Item 2' },
	{ id: '3', value: 'Item 3' },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState('');
const filteredOptions = React.useMemo(() => {
	if (searchTerm === '') return initialOptions;
	return initialOptions.filter((item) =>
		item.value.toLowerCase().includes(searchTerm.toLowerCase())
	);
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
	setSelectedOption(selectedOption);
	setSearchTerm('');
};

return (
	<Field isDisabled label="Select Items">
		<Combobox
			inputValue={searchTerm || selectedOption?.value}
			menuTrigger="focus"
			onClear={() => setSearchTerm('')}
			onClose={() => setSearchTerm('')}
			onInputChange={setSearchTerm}
			onSelectionChange={clearAndSelect}
			options={filteredOptions}
			selectedKey="value"
			selectedOption={selectedOption}
		>
			<ComboboxSearchInput placeholder="Search..." />
			<ComboboxPopover>
				<ComboboxListbox
					noResultsFallback={
						<Text className="text-secondary text-center text-body-12 py-4">
							No matching results
						</Text>
					}
					options={filteredOptions}
				>
					{(item) => <ComboboxItem option={item}>{item.value}</ComboboxItem>}
				</ComboboxListbox>
			</ComboboxPopover>
		</Combobox>
	</Field>
);

Disabled MenuItem

Utilize the isDisabled prop in the <ComboboxItem /> component to indicate that a specific item is not selectable.

This enhances user experience by clearly displaying the disabled state. Additionally, for improved accessibility, keyboard navigation will bypass disabled MenuItems in the Listbox.

const initialOptions = [
	{ id: '1', value: 'Item 1', disabled: true },
	{ id: '2', value: 'Item 2', disabled: false },
	{ id: '3', value: 'Item 3', disabled: true },
	{ id: '4', value: 'Item 4', disabled: false },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState('');
const filteredOptions = React.useMemo(() => {
	console.log('searchTerm', searchTerm);
	if (searchTerm === '') return initialOptions;
	return initialOptions.filter((item) =>
		item.value.toLowerCase().includes(searchTerm.toLowerCase())
	);
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
	console.log('selectedOption', selectedOption);
	setSelectedOption(selectedOption);
	setSearchTerm('');
};

return (
	<Field label="Select Items">
		<Combobox
			inputValue={searchTerm || selectedOption?.value}
			menuTrigger="focus"
			onClear={() => setSearchTerm('')}
			onClose={() => setSearchTerm('')}
			onInputChange={setSearchTerm}
			onSelectionChange={clearAndSelect}
			selectedKey="value"
			selectedOption={selectedOption}
		>
			<ComboboxSearchInput placeholder="Search..." />
			<ComboboxPopover>
				<ComboboxListbox
					noResultsFallback={
						<Text className="text-secondary text-center text-body-12 py-4">
							No matching results
						</Text>
					}
					options={filteredOptions}
				>
					{(item) => <ComboboxItem option={item} isDisabled={item.disabled}>{item.value}</ComboboxItem>}
				</ComboboxListbox>
			</ComboboxPopover>
		</Combobox>
	</Field>
);

Note: Disabled item can already be selected option but having any interactions on it won't be possible.

ComboBox Group

The Combobox component supports displaying options in groups, which is useful for organizing related items into categories. This example demonstrates how to use the ComboboxListBoxGroup and ComboboxListGroup components to create a groups in combobox.

const initialOptions = [
  {
    label: "Leaf",
    options: [
      { id: "1", value: "Cabbage" },
      { id: "2", value: "Spinach" },
      { id: "3", value: "Wheat grass" },
    ],
  },
  {
    label: "Beans",
    options: [
      { id: "6", value: "Chickpea" },
      { id: "7", value: "Green bean" },
      { id: "8", value: "Horse gram" },
    ],
  },
  {
    label: "Bulb",
    options: [
      { id: "9", value: "Garlic" },
      { id: "10", value: "Onion" },
      { id: "11", value: "Nopal" },
      { id: "12", value: "Ginger" },
      { id: "13", value: "Ginseng" },
    ],
  },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState("");

const filteredOptions = React.useMemo(() => {
  if (searchTerm === "") return initialOptions;
  return initialOptions.reduce((filtered, { label, options }) => {
    const matchingOptions = options.filter((item) =>
      item.value.toLowerCase().includes(searchTerm.toLowerCase())
    );

    if (matchingOptions.length > 0) {
      filtered.push({ label, options: matchingOptions });
    }

    return filtered;
  }, []);
}, [searchTerm]);

const clearAndSelect = (selectedOption) => {
  setSelectedOption(selectedOption);
  setSearchTerm("");
};

return (
  <Field label="Select vegetable">
    <Combobox
      inputValue={searchTerm || selectedOption?.value}
      menuTrigger="focus"
      onClear={() => setSearchTerm("")}
      onClose={() => setSearchTerm("")}
      onInputChange={setSearchTerm}
      onSelectionChange={clearAndSelect}
      selectedKey="value"
      selectedOption={selectedOption}
    >
      <ComboboxSearchInput placeholder="Search..." />
      <ComboboxPopover>
        <ComboboxListBoxGroup
          options={filteredOptions}
          noResultsFallback={
            <Text className="text-secondary text-center text-body-12 py-4">
							No matching results
						</Text>
          }
        >
          {({ options, label }) => {
            return (
              <ComboboxListGroup label={label} options={options}>
                {(item) => (
                  <ComboboxItem
                    option={item}
                    onClick={() => {
                      setSelectedOption(item);
                    }}
                  >
                    {item.value}
                  </ComboboxItem>
                )}
              </ComboboxListGroup>
            );
          }}
        </ComboboxListBoxGroup>
      </ComboboxPopover>
    </Combobox>
  </Field>
);

FullScreen on Mobile

On mobile, enable fullScreenForMobile to render the sheet in full-screen with a default close button.

const initialOptions = [
  { id: "1", value: "Item 1" },
  { id: "2", value: "Item 2" },
  { id: "3", value: "Item 3" },
];
const [selectedOption, setSelectedOption] = React.useState();
const [searchTerm, setSearchTerm] = React.useState("");
const filteredOptions = React.useMemo(() => {
  if (searchTerm === "") return initialOptions;
  return initialOptions.filter((item) =>
    item.value.toLowerCase().includes(searchTerm.toLowerCase())
  );
}, [initialOptions, searchTerm]);

const clearAndSelect = (selectedOption) => {
  setSelectedOption(selectedOption);
  setSearchTerm("");
};

return (
  <Field label="Select Items">
    <Combobox
      inputValue={searchTerm || selectedOption?.value}
      onClear={() => setSearchTerm("")}
      onInputChange={setSearchTerm}
      onSelectionChange={clearAndSelect}
      options={filteredOptions}
      selectedKey="value"
      selectedOption={selectedOption}
      fullScreenForMobile
    >
      <ComboboxSearchInput placeholder="Search..." />
      <ComboboxPopover>
        <ComboboxListbox
          noResultsFallback={
            <Text className="text-secondary text-center text-body-12 py-4">
              No matching results
            </Text>
          }
          options={filteredOptions}
        >
          {(item) => <ComboboxItem option={item}>{item.value}</ComboboxItem>}
        </ComboboxListbox>
      </ComboboxPopover>
    </Combobox>
  </Field>
);

API Reference

Combobox

PropTypeDescriptionDefault
children((menuState: { isMenuOpen: boolean }) => React.ReactNode) | React.ReactNodeAccepts either a React node or a render function. The render function provides the menu's state (isMenuOpen)._
closeButtonPropsForMobile?{ label: string, onClick: function, size: 'large' | 'standard' | 'small' }If closeButtonPropsForMobile is provided then the mobile version of the component will have a close button_
selectedKeykeyOf objectKey for identifying the selected option._
selectedOptionobject | undefinedCurrently selected option from the list._
inputValue?stringValue of the combobox input._
menuTrigger?'focus'| 'input'Interaction type to display the Combobox menu.input
mobileFriendly?booleanIndicates if the opened element should be rendered as a Sheet in mobile viewportstrue
onClear?() => voidFunction to be invoked for clearing the Combobox input value._
onClose?() => voidHandler that is called when the Combobox is closed._
onInputChange(value: string) => voidFunction to be invoked when the input value changes._
onSelectionChange(newOption: object | undefined) => voidFunction to be invoked when the selection changes._
popoverMatchReferenceWidth?booleanMatch the width of the popover with the reference element.false
popoverMaxHeight?numberThe max height of the popover.356
popoverMaxWidth?numberThe max width of the popover.400
popoverOffset?numberThe offset of the combobox popover.4
popoverPlacement?'bottom' | 'bottom-start' | 'bottom-end'The placement of the popover relative to the combobox Input.'bottom-start'
strategy?'absolute' | 'fixed'The strategy used to position the floating element.'absolute'
titleForMobile?stringOn mobile Combobox renders a Sheet component. If titleForMobile is provided then the Sheet will have a Header with title rendered_
fullScreenForMobilebooleanEnables fullscreen mode for the mobile select menu, making it cover the entire viewport.false

ComboboxInput

This API applies to both ComboboxSearchInput and ComboboxTextInput.

PropTypeDescriptionDefault
aria-activedescendant?stringidentifies the currently active element when using ARIA widgets._
aria-autocomplete?'inline' | 'list' | 'both' | 'none'Indicates whether input completion suggestions are provided, and their type._
aria-controls?stringIdentifies the element(s) that the input controls._
aria-expanded?booleanIndicates whether the popover is currently expanded or collapsed._
aria-haspopup?'dialog' | 'grid' | 'listbox' | 'menu' | 'tree' | 'boolean'Indicates the availability of a popup related to the input._
autoComplete?stringSpecifies whether autocomplete is enabled for the input._
autoCorrect?'on' | 'off'Specifies whether auto-correction is enabled for the input._
autoFocus?booleanAutomatically focuses the input element when it is rendered._
adornmentStart?React.ReactNodeSlot to render content before the input's value._
adornmentEnd?React.ReactNodeSlot to render content after the input's value._
focusContainerRef?React.Ref<HTMLDivElement>Reference to the wrapper FocusContainer element._
inputMode?'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search'Hints to browsers about what kind of virtual keyboard to display._
name?stringName of the input, used for form submissions._
onBlur?functionFunction to be invoked when the input loses focus._
onChange?functionFunction to be invoked when a new item is selected._
onFocus?functionFunction to be invoked when the input is focused._
onKeyDown?functionFunction to be invoked when a key is pressed while the input is focused._
onPaste?functionFunction to be invoked when content is pasted into the input._
pattern?stringRegular expression pattern the input's value must match for validation._
placeholder?stringPlaceholder text displayed when the input is empty._
role?stringARIA role for the input._
spellCheck?booleanSpecifies whether the input value should be checked for spelling errors._
type?'email' | 'password' | 'search' | 'tel' | 'text' | 'url'Type of the input element._

ComboboxPopover

PropTypeDescriptionDefault
shouldUsePortal?booleanDetermines whether the Popover should be rendered in a React Portal. If true, the Popover will be rendered outside the DOM hierarchy of the parent component.true
children?React.ReactNodeContent of the ComboboxList with the options._
inputAppearance?"SearchInput" | "TextInput" | "none"Controls whether to include or exclude an input inside the mobile popover / sheet."TextInput"
inputPlaceholder?stringThe placeholder text for the input inside the mobile popover / sheet."Search..."

ComboboxListbox

PropTypeDescriptionDefault
noResultsFallback?React.ReactNodeComponent to render when there are no options left in the filtered result._
optionsArray of ObjectsOptions to be rendered in the dropdown._

ComboboxItem

PropTypeDescriptionDefault
childrenReact.ReactNodeThe content of the combobox menu item._
id?stringAn optional ID for the menu item; auto-generated if not provided._
optionobjectOption associated with the item_
onClick?() => voidFunction to be invoked when the item is clicked._
size?'standard'|'large'Size of the combobox item.standard
showSelectionIndicator?booleanControls whether to show the selection indicator (check icon) for selected items.true

Style API

Our design system components include style props that allow you to easily customize different parts of each component to match your design needs.

Please refer to the Style API documentation for more insights.