# Tag field API

> Explore the API of Cimpress UI's tag field component.

Source: https://ui.cimpress.io/components/tag-field/api/

:::caution[Deprecated]
Tag field is deprecated. See the [migration guide](#migration-to-select) below for more details.
:::

## Import

Cimpress UI exports three tag field-related components:

- `TagField`: main component that allows users to select multiple items from a collapsible list.
- `TagFieldItem`: component that renders a single selectable item within a tag field.
- `TagFieldSection`: component that groups related tag field items together under a section title.

```tsx
import { TagField, TagFieldItem, TagFieldSection } from '@cimpress-ui/react';
```

## Migration to select

Tag field can be migrated to select by using the following mapping:

| `TagField`                                      | `Select`                                      |
| :---------------------------------------------- | :-------------------------------------------- |
| `TagField` / `TagFieldItem` / `TagFieldSection` | `Select` / `SelectItem` / `SelectSection`     |
| `selectedKeys` / `defaultSelectedKeys`          | `value` / `defaultValue` (`Key[]`, not `Set`) |
| `onSelectionChange(set)`                        | `onChange(keys)`                              |
| (always filterable)                             | `isFilterable`                                |

```tsx
// Before
<TagField label="Favorite fruits" defaultSelectedKeys={['apple', 'cherry']}>
  <TagFieldItem id="apple">Apple</TagFieldItem>
  <TagFieldItem id="banana">Banana</TagFieldItem>
  <TagFieldItem id="cherry">Cherry</TagFieldItem>
</TagField>

// After
<Select label="Favorite fruits" selectionMode="multiple" isFilterable defaultValue={['apple', 'cherry']}>
  <SelectItem id="apple">Apple</SelectItem>
  <SelectItem id="banana">Banana</SelectItem>
  <SelectItem id="cherry">Cherry</SelectItem>
</Select>
```

## Controlled/uncontrolled usage

```tsx
import { Stack, TagField, TagFieldItem, type Selection } from '@cimpress-ui/react';
import { useState } from 'react';

export default function Demo() {
  const [selectedKeys, setSelectedKeys] = useState<Selection>(() => new Set(['apple', 'cherry']));

  return (
    <Stack gap={32}>
      <TagField label="Favorite fruits (controlled)" selectedKeys={selectedKeys} onSelectionChange={setSelectedKeys}>
        <TagFieldItem id="apple">Apple</TagFieldItem>
        <TagFieldItem id="banana">Banana</TagFieldItem>
        <TagFieldItem id="cherry">Cherry</TagFieldItem>
      </TagField>

      <TagField label="Favorite fruits (uncontrolled)" defaultSelectedKeys={['apple', 'cherry']}>
        <TagFieldItem id="apple">Apple</TagFieldItem>
        <TagFieldItem id="banana">Banana</TagFieldItem>
        <TagFieldItem id="cherry">Cherry</TagFieldItem>
      </TagField>
    </Stack>
  );
}
```

## Imperative API

```tsx
import { Button, Stack, TagField, type TagFieldApi, TagFieldItem } from '@cimpress-ui/react';
import { useRef } from 'react';

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

  return (
    <Stack gap={16}>
      <TagField label="Favorite fruits" defaultSelectedKeys={['apple', 'cherry']} apiRef={apiRef}>
        <TagFieldItem id="apple">Apple</TagFieldItem>
        <TagFieldItem id="banana">Banana</TagFieldItem>
        <TagFieldItem id="cherry">Cherry</TagFieldItem>
      </TagField>

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

## Accessibility notes

Tag field 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 tag field 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.

The list of tags displayed next to the field is a single tab stop within the page's tab order. Use the Tab key to navigate to the list, and the arrow keys to navigate between tags within the list. Use the Backspace or Delete key to remove tags from the list.

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

## Collections

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

## Forms

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

## API reference

### TagField

Allows users to filter a collapsible list and select multiple items from it.

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

**Deprecated:** Use [select](https://ui.cimpress.io/components/select) instead.

- `ref`: `Ref<HTMLDivElement>`

  The `ref` type for this component.

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

- `selectedKeys`: `Iterable<Key, any, any>`

  The currently selected keys in the collection (controlled).

- `defaultSelectedKeys`: `Iterable<Key, any, any>`

  The initial selected keys in the collection (uncontrolled).

- `onSelectionChange`: `(keys: Set<Key>) => void`

  Handler that is called when the selection changes.

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

- `renderEmptyState`: `() => ReactNode`

  Provides content to display when there are no tags in the group.

- `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: TagFieldValidationValue) => 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.

- `apiRef`: `RefObject<TagFieldApi | 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`.

### TagFieldItem

Renders a single list item within `TagField`.

**Deprecated:** Use [select](https://ui.cimpress.io/components/select) instead.

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

### TagFieldSection

Groups list items within `TagField` into a section.

**Deprecated:** Use [select](https://ui.cimpress.io/components/select) instead.

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