# Combo box API

> Explore the API of Cimpress UI's combo box component.

Source: https://ui.cimpress.io/components/combo-box/api/

## Import

Cimpress UI exports three combo box-related components:

- `ComboBox`: main component that allows users to select one item from a collapsible list with search functionality.
- `ComboBoxItem`: component that renders a single selectable item within a combo box.
- `ComboBoxSection`: component that groups related combo box items together under a section title.

```tsx
import { ComboBox, ComboBoxItem, ComboBoxSection } from '@cimpress-ui/react';
```

## Controlled/uncontrolled usage

```tsx
import { ComboBox, ComboBoxItem, Stack, type Key } from '@cimpress-ui/react';
import { useState } from 'react';

export default function Demo() {
  const [value, setValue] = useState<Key | null>('apple');

  return (
    <Stack gap={32}>
      <ComboBox label="Favorite fruit (controlled)" value={value} onChange={setValue}>
        <ComboBoxItem id="apple">Apple</ComboBoxItem>
        <ComboBoxItem id="banana">Banana</ComboBoxItem>
        <ComboBoxItem id="cherry">Cherry</ComboBoxItem>
      </ComboBox>

      <ComboBox label="Favorite fruit (uncontrolled)" defaultInputValue="Apple" defaultValue="apple">
        <ComboBoxItem id="apple">Apple</ComboBoxItem>
        <ComboBoxItem id="banana">Banana</ComboBoxItem>
        <ComboBoxItem id="cherry">Cherry</ComboBoxItem>
      </ComboBox>
    </Stack>
  );
}
```

## Imperative API

```tsx
import { Button, ComboBox, type ComboBoxApi, ComboBoxItem, Stack } from '@cimpress-ui/react';
import { useRef } from 'react';

export default function Demo() {
  const apiRef = useRef<ComboBoxApi>(null);

  return (
    <Stack gap={16}>
      <ComboBox label="Favorite fruit" defaultValue="apple" apiRef={apiRef}>
        <ComboBoxItem id="apple">Apple</ComboBoxItem>
        <ComboBoxItem id="banana">Banana</ComboBoxItem>
        <ComboBoxItem id="cherry">Cherry</ComboBoxItem>
      </ComboBox>

      <Stack gap={16} direction={{ md: 'horizontal' }}>
        <Button onPress={() => apiRef.current?.focus()}>Focus</Button>
        <Button onPress={() => apiRef.current?.select()}>Select text</Button>
      </Stack>
    </Stack>
  );
}
```

## Accessibility notes

Combo box follows the [ARIA combobox pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/). See the linked page for a list of available keyboard interactions.

Collapsible combo box list follows the [ARIA listbox pattern](https://www.w3.org/WAI/ARIA/apg/patterns/listbox/). See the linked page for a list of available keyboard interactions.

When the `isClearable` prop is enabled, pressing the Escape key will clear the current selection, if the combo box is focused and the dropdown (popover) is not open.

`ComboBox` requires a textual label to remain accessible to assistive technologies. See our [accessibility guide](/dev-guides/accessibility#labelling) for more details.

## Collections

Combo box is a collection component. See our [collection components guide](/dev-guides/collection-components) to learn how to work with collections.

## Forms

Combo box can integrate with native HTML forms. See our [forms guide](/dev-guides/forms) to learn how to work with forms.

## API reference

### ComboBox

Allows users to filter a collapsible list and select one item from it.

See [combo box usage guidelines](https://ui.cimpress.io/components/combo-box)

- `ref`: `Ref<HTMLDivElement>`

  The `ref` type for this component.

**Props: `ComboBoxProps<T extends CollectionItem = CollectionItem>`**

- `value`: `Key | null`

  The current value (controlled).

- `defaultValue`: `Key`

  The initial value (uncontrolled).

- `onChange`: `(key: Key | null) => void`

  Handler that is called when the value changes.

- ~~`selectedKey`~~: `Key | null`

  The currently selected key in the collection (controlled).

  **Deprecated:** Use `value` instead.

- ~~`defaultSelectedKey`~~: `Key`

  The initial selected key in the collection (uncontrolled).

  **Deprecated:** Use `defaultValue` instead.

- ~~`onSelectionChange`~~: `(key: Key | null) => void`

  Handler that is called when the selection changes.

  **Deprecated:** Use `onChange` instead.

- `isClearable`: `boolean`

  Whether to display a clear button to clear the selection.

- `isVirtualized`: `boolean`

  Whether the list of options should be virtualized. Use this as a performance optimization for large lists.

  Defaults to `false`.

- `onScroll`: `UIEventHandler<HTMLDivElement>`

  Handler that is called when the list of items is scrolled.

- `id`: `string`

  The element's unique identifier. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id).

- `data-cim-style-root`: `boolean`

  Use this attribute to "claim" the component tree for exclusive Cimpress UI usage.

- `UNSAFE_className`: `string`

  Sets the CSS className for the element. Only use as a **last resort**. Use style props instead.

  See [styling guide](https://ui.cimpress.io/dev-guides/styling/).

- `UNSAFE_style`: `CSSProperties`

  Sets the CSS style for the element. Only use as a **last resort**. Use style props instead.

  See [styling guide](https://ui.cimpress.io/dev-guides/styling/).

- `label`: `string`

  The content to display as the label.

- `aria-label`: `string`

  Defines a string value that labels the current element.

- `aria-labelledby`: `string`

  Identifies the element (or elements) that labels the current element.

- `aria-describedby`: `string`

  Identifies the element (or elements) that describes the object.

- `aria-details`: `string`

  Identifies the element (or elements) that provide a detailed, extended description for the object.

- `form`: `string`

  The `<form>` element to associate the input with.
  The value of this attribute must be the id of a `<form>` in the same document.
  See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form).

- `name`: `string`

  The name of the input element, used when submitting an HTML form. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#name).

- `description`: `string`

  A description for the field. Provides a hint such as specific requirements for what to choose.

- `error`: `FieldError`

  An error message for the field.

- `validate`: `(value: ComboBoxValidationValue) => string | true | string[] | undefined`

  A function that returns an error message (or `true`) if a given value is invalid.
  Validation errors are displayed to the user when the form is submitted.
  For real-time validation, use the `error` prop instead.

- `placeholder`: `string`

  The placeholder text displayed in the input field.

- `children`: `ReactNode | ((item: T) => ReactNode)`

  The contents of the collection.

- `items`: `Iterable<T, any, any>`

  The items to display in the collection.

- `isLoading`: `boolean`

  Whether items are currently being loaded.

- `onLoadMore`: `() => void`

  A callback function that is called when more items should be loaded.

- `apiRef`: `RefObject<ComboBoxApi | null>`

  A React ref that allows access to the imperative API of this component.

- `onFocus`: `(e: FocusEvent<HTMLInputElement>) => void`

  Handler that is called when the element receives focus.

- `onBlur`: `(e: FocusEvent<HTMLInputElement>) => void`

  Handler that is called when the element loses focus.

- `autoFocus`: `boolean`

  Whether the element should receive focus on render.

- `isRequired`: `boolean`

  Whether user input is required on the input before form submission.

- `isInvalid`: `boolean`

  Whether the input value is invalid.

- `isDisabled`: `boolean`

  Whether the input is disabled.

- `isReadOnly`: `boolean`

  Whether the input can be selected but not changed by the user.

- `onOpenChange`: `(isOpen: boolean, menuTrigger?: MenuTriggerAction) => void`

  Method that is called when the open state of the menu changes. Returns the new open state and
  the action that caused the opening of the menu.

- `inputValue`: `string`

  The value of the ComboBox input (controlled).

- `defaultInputValue`: `string`

  The default value of the ComboBox input (uncontrolled).

- `onInputChange`: `(value: string) => void`

  Handler that is called when the ComboBox input value changes.

**Props: `StyleProps`**

- `margin`: `Responsive<Spacing | "auto">`

  The amount of margin applied to all edges of this component.

- `marginX`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the left and right edges of this component. Takes priority over `margin`.

- `marginY`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the top and bottom edges of this component. Takes priority over `margin`.

- `marginTop`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the top edge of this component. Takes priority over `marginY` and `margin`.

- `marginRight`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the right edge of this component. Takes priority over `marginX` and `margin`.

- `marginBottom`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the bottom edge of this component. Takes priority over `marginY` and `margin`.

- `marginLeft`: `Responsive<Spacing | "auto">`

  The amount of margin applied to the left edge of this component. Takes priority over `marginX` and `margin`.

### ComboBoxItem

Renders a single list item within `ComboBox`.

**Props: `ComboBoxItemProps<T extends CollectionItem>`**

- `children` (required): `StringLikeChildren`

  The content to display as the label.

- `id`: `Key`

  The ID of the item. Has to be unique across all sections and items.

- `onHoverStart`: `(e: HoverEvent) => void`

  Handler that is called when a hover interaction starts.

- `onHoverEnd`: `(e: HoverEvent) => void`

  Handler that is called when a hover interaction ends.

- `isDisabled`: `boolean`

  Whether the item is disabled.

### ComboBoxSection

Groups list items within `ComboBox` into a section.

**Props: `ComboBoxSectionProps<T extends CollectionItem>`**

- `title` (required): `string`

  The content to display as the section title.

- `id`: `Key`

  The ID of the section. Has to be unique across all sections and items.

- `children`: `ReactNode | ((item: T) => ReactNode)`

  The contents of the collection.

- `items`: `Iterable<T, any, any>`

  The items to display in the collection.
