# Select API

> Explore the API of Cimpress UI's select component.

Source: https://ui.cimpress.io/components/select/api/

## Import

Cimpress UI exports three select-related components:

- `Select`: main component that allows users to select one or more items from a collapsible list.
- `SelectItem`: component that renders a single selectable item within a select.
- `SelectSection`: component that groups related select items together under a section title.

```tsx
import { Select, SelectItem, SelectSection } from '@cimpress-ui/react';
```

## Controlled/uncontrolled usage

```tsx
import { Select, SelectItem, 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}>
      <Select label="Favorite fruit (controlled)" value={value} onChange={setValue}>
        <SelectItem id="apple">Apple</SelectItem>
        <SelectItem id="banana">Banana</SelectItem>
        <SelectItem id="cherry">Cherry</SelectItem>
      </Select>

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

## Imperative API

```tsx
import { Button, Select, type SelectApi, SelectItem, Stack } from '@cimpress-ui/react';
import { useRef } from 'react';

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

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

      <Button onPress={() => apiRef.current?.focus()}>Focus</Button>
    </Stack>
  );
}
```

## Accessibility notes

Collapsible select list can be opened by focusing on the select trigger and pressing Enter, Space, Up Arrow, or Down Arrow.

Collapsible select 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.

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

## Collections

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

## Forms

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

## Asynchronous loading

Select supports loading the list of items asynchronously. This can be beneficial for very long lists - you can load a partial list and then load more items once the user scrolls past the last loaded item.
If your select is filterable, you can also load filtering results asynchronously, based on the filter value.

To implement asynchronous loading, use the `isLoading` and `onLoadMore` props.

```tsx
import { Select, SelectItem, type CollectionItem } from '@cimpress-ui/react';
import { LocalizationProvider } from '@cimpress-ui/react/i18n';
import { QueryClient, useInfiniteQuery } from '@tanstack/react-query';
import { useMemo, useState } from 'react';

interface Character extends CollectionItem {
  name: string;
}

const queryClient = new QueryClient();

export default function Demo() {
  const [selectedItem, setSelectedItem] = useState<Character | null>(null);
  const [filterValue, setFilterValue] = useState('');

  const { data, isLoading, hasNextPage, isFetching, fetchNextPage } = useInfiniteQuery(
    {
      queryKey: ['star-wars-characters', filterValue],
      queryFn: async ({ signal, pageParam: nextUrl }) => {
        if (filterValue === '') {
          return {
            data: [],
          };
        }

        const response = await fetch(nextUrl || `https://swapi.py4e.com/api/people?search=${filterValue}`, {
          signal,
        });

        await new Promise((resolve) => setTimeout(() => resolve(null), 1000));

        if (!response.ok) {
          throw new globalThis.Error('Network response was not OK');
        }

        const { results, next } = (await response.json()) as {
          results: { name: string }[];
          next: string | null;
        };

        return {
          data: results.map<Character>(({ name }) => ({ id: name, name })),
          nextUrl: next,
        };
      },
      initialPageParam: '',
      getNextPageParam: (lastPage) => lastPage.nextUrl,
    },
    queryClient,
  );

  const items = useMemo(() => {
    const items = data?.pages.flatMap((page) => page.data) ?? [];

    // Ensure the currently selected item is present in the list to maintain selection after filtering
    if (selectedItem && !items.some((i) => i.id === selectedItem.id)) {
      items.push(selectedItem);
    }

    return items;
  }, [data, selectedItem]);

  return (
    <LocalizationProvider
      messages={{
        collection: {
          emptyList: 'Start typing to see results.',
        },
      }}
    >
      <Select
        label="Favorite Star Wars character"
        items={items}
        value={selectedItem?.id ?? null}
        onChange={(key) => {
          setSelectedItem(items.find((item) => item.id === key) ?? null);
        }}
        isFilterable
        filterValue={filterValue}
        onFilterChange={setFilterValue}
        isLoading={isLoading || isFetching}
        onLoadMore={() => hasNextPage && !isFetching && fetchNextPage()}
      >
        {(item) => <SelectItem>{item.name}</SelectItem>}
      </Select>
    </LocalizationProvider>
  );
}
```

## API reference

### Select

Allows users to select one or more items from a collapsible list.

See [select usage guidelines](https://ui.cimpress.io/components/select/).

- `ref`: `Ref<HTMLDivElement>`

  The `ref` type for this component.

**Props: `SelectProps<T extends CollectionItem = CollectionItem, M extends SelectSelectionMode = 'single'>`**

- `selectionMode`: `M`

  The selection mode of the select.

  Defaults to `'single'`.

- `value`: `M extends 'single' ? Key | null : Key[]`

  The current value (controlled).

- `defaultValue`: `M extends 'single' ? Key : Key[]`

  The initial value (uncontrolled).

- `onChange`: `(key: M extends 'single' ? Key | null : Key[]) => void`

  Handler that is called when the value changes.

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

  The currently selected key in the collection (controlled).

  **Deprecated:** Use `value` instead. Not compatible with `selectionMode="multiple"`.

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

  The initial selected key in the collection (uncontrolled).

  **Deprecated:** Use `defaultValue` instead. Not compatible with `selectionMode="multiple"`.

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

  Handler that is called when the selection changes.

  **Deprecated:** Use `onChange` instead. Not compatible with `selectionMode="multiple"`.

- `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.

- `isFilterable`: `boolean`

  Whether the list of options should be filterable.

  Defaults to `false`.

- `filterValue`: `string`

  The value of the filter input (controlled).

- `defaultFilterValue`: `string`

  The initial value of the filter input (uncontrolled).

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

  Handler that is called when the filter value changes.

- `UNSTABLE_filter`: `((textValue: string, inputValue: string, item: { key: Key; value: T | null }) => boolean) | null`

  A custom filter function to use instead of the default filter.

- `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: M extends 'single' ? Key : Key[]) => 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.

- `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<SelectApi | null>`

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

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

  Handler that is called when the element receives focus.

- `onBlur`: `(e: FocusEvent<Element>) => 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.

- `autoComplete`: `string`

  Describes the type of autocomplete functionality the input should provide if any. See
  [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefautocomplete).

- `placeholder`: `string`

  Temporary text that occupies the select when it is empty.

  Defaults to `'Select an item' (localized)`.

- `onOpenChange`: `(isOpen: boolean) => void`

  Method that is called when the open state of the menu 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`.

### SelectItem

Renders a single list item within `Select`.

**Props: `SelectItemProps`**

- `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.

- `description`: `string`

  Additional description for the item.

- `icon`: `ReactNode`

  A non-interactive piece of content displayed at the start of the item.

- `UNSTABLE_meta`: `ReactNode`

  A non-interactive piece of content displayed at the end of the item.

- `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.

### SelectSection

Groups list items within `Select` into a section.

**Props: `SelectSectionProps<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.
