> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# createTagsPlugin

> This plugin lets you manage and display tags in Autocomplete.

<Tip>
  Autocomplete is also available as an experimental widget in InstantSearch,
  making it easier to integrate into your search experience.
  For more information,
  see the API reference for [InstantSearch.js](/doc/api-reference/widgets/autocomplete/js) or
  [React InstantSearch](/doc/api-reference/widgets/autocomplete/react).
</Tip>

This plugin lets you manage and display tags in Autocomplete.
You can use tags in various ways, such as [displaying filters](/doc/ui-libraries/autocomplete/guides/filtering-results) or representing navigation steps.

## Install the plugin

<CodeGroup>
  ```sh npm theme={"system"}
  npm install @algolia/autocomplete-plugin-tags
  ```

  ```sh yarn theme={"system"}
  yarn add @algolia/autocomplete-plugin-tags
  ```
</CodeGroup>

## Import the plugin into your project

```js JavaScript icon=code theme={"system"}
import { autocomplete } from "@algolia/autocomplete-js";
import { createTagsPlugin } from "@algolia/autocomplete-plugin-tags";

const tagsPlugin = createTagsPlugin();

autocomplete({
  // ...
  container: "#autocomplete",
  plugins: [tagsPlugin],
});
```

The plugin includes CSS compatible with [`autocomplete-theme-classic`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-theme-classic).

```js JavaScript icon=code theme={"system"}
import "@algolia/autocomplete-plugin-tags/dist/theme.min.css";
```

If you don't use a package manager, you can use the HTML `script` element:

```html HTML icon=code-xml theme={"system"}
<script
  src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-tags@1.19.9/dist/umd/index.production.js"
  integrity="sha256-m15NuZIZ6jTQq1uNRug0NYOuElnppLH+/9ZLJNvRQ4o="
  crossorigin="anonymous"
></script>
<script>
  const { createTagsPlugin } = window["@algolia/autocomplete-plugin-tags"];
</script>
```

To load the tags plugin's theme:

```html HTML icon=code-xml theme={"system"}
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-tags@1.19.9/dist/umd/index.production.js"
  integrity="sha256-m15NuZIZ6jTQq1uNRug0NYOuElnppLH+/9ZLJNvRQ4o="
  crossorigin="anonymous"
/>
```

## Initialize the plugin with `initialTags`

The plugin lets you pass [`initialTags`](#param-initial-tags) for Autocomplete.
Use it when deriving tags from an existing state, such as the route or filter status.

For example, if the URL reflects the current filter state,
you can initialize the plugin with them when the page loads before the Autocomplete instance starts.

```js JavaScript icon=code theme={"system"}
// Current URL: https://example.org/?category=Phones&brand=Apple

const parameters = Array.from(new URLSearchParams(location.search));
const initialTags = parameters.map(([facet, label]) => ({ label, facet }));
// [{ label: 'Phones', facet: 'category' }, { label: 'Apple', facet: 'brand' }]

const tagsPlugin = createTagsPlugin({ initialTags });
```

## Modify tags

By default, the plugin populates a source with the current tags.
Users can navigate through them as with any other source and delete them on click or selection.
You can customize the source with [`transformSource`](#param-transform-source).

If you want to display tags manually,
for example, with the [`render`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-render)
function or in the search box, you can prevent the plugin from returning a source.
The plugin exposes an API on the [Context](/doc/ui-libraries/autocomplete/core-concepts/context) to let you access tags.

<CodeGroup>
  ```js JavaScript theme={"system"}
  // ...
  const tagsPlugin = createTagsPlugin({
    // ...
    transformSource({ source }) {
      return undefined;
    },
  });

  autocomplete({
    // ...
    render({ sections, html, render }, root) {
      render(
        html`<div class="aa-PanelLayout aa-Panel--scrollable">
          <ul>
            ${state.context.tagsPlugin.tags.map(
              (tag) =>
                html`<li key="${tag.label}" onClick="${() => tag.remove()}">
                  ${tag.label}
                </li>`,
            )}
          </ul>
          <div>${sections}</div>
        </div>`,
        root,
      );
    },
  });
  ```

  ```jsx JSX theme={"system"}
  // ...
  const tagsPlugin = createTagsPlugin({
    // ...
    transformSource({ source }) {
      return undefined;
    },
  });

  autocomplete({
    // ...
    render({ sections, state }, root) {
      render(
        <div classbody="aa-PanelLayout aa-Panel--scrollable">
          <ul>
            {state.context.tagsPlugin.tags.map((tag) => (
              <li key={tag.label} onClick={() => tag.remove()}>
                {tag.label}
              </li>
            ))}
          </ul>
          <div>{sections}</div>
        </div>,
        root,
      );
    },
  });
  ```
</CodeGroup>

<Note>
  Returned tags expose a `remove` function for removing individual tags.
</Note>

The plugin also exposes an [`addTags`](#param-add-tags) and a [`setTags`](#param-set-tags) function on the [context](/doc/ui-libraries/autocomplete/core-concepts/context) to update the list of tags.

<CodeGroup>
  ```js JavaScript theme={"system"}
  // ...

  autocomplete({
    // ...
    render({ sections, state, html, render }, root) {
      render(
        html`<div class="aa-PanelLayout aa-Panel--scrollable">
          <button onClick="${() => state.context.tagsPlugin.setTags([])}">
            Clear all tags
          </button>
          /* ... */
        </div>`,
        root,
      );
    },
  });
  ```

  ```jsx JSX theme={"system"}
  // ...

  autocomplete({
    // ...
    render({ sections, state }, root) {
      render(
        <div classbody="aa-PanelLayout aa-Panel--scrollable">
          <button onClick={() => state.context.tagsPlugin.setTags([])}>
            Clear all tags
          </button>
          {/* ... */}
        </div>,
        root,
      );
    },
  });
  ```
</CodeGroup>

You can access the same API to retrieve and modify tags directly on the plugin.
This is helpful when interacting with tags outside the Autocomplete instance.

```js JavaScript icon=code theme={"system"}
document.getElementById("#clear-speakers").addEventListener("click", () => {
  tagsPlugin.data.setTags([]);
});
```

## Parameters

<ParamField body="initialTags" type="BaseTag<TTag>[]">
  A set of initial tags to pass to the plugin.

  You can use this to pass initial refinements (for example, from local state)
  without triggering the Autocomplete lifecycle.

  ```ts TypeScript icon=code theme={"system"}
  type BaseTag<TTag = Record<string, unknown>> = TTag & { label: string };
  ```
</ParamField>

<ParamField body="getTagsSubscribers" type="(): Array<{ sourceId: string, getTag(params: { item: TItem }): BaseTag<TTag> }>">
  A function to specify what sources the plugin should subscribe to.
  The plugin adds a tag when selecting an item from these sources.

  * `sourceId`: the `sourceId` of the source to subscribe to.
  * `getTag`: a function to return a tag from the selected items.

  ```js JavaScript icon=code theme={"system"}
  const tagsPlugin = createTagsPlugin({
    getTagsSubscribers() {
      return [
        {
          sourceId: "brands",
          getTag({ item }) {
            return {
              ...item,
              label: item.name,
            };
          },
        },
      ];
    },
  });
  ```
</ParamField>

<ParamField body="transformSource" type="function">
  ```ts Type definition theme={"system"}
  (params: {
    source: AutocompleteSource<Tag<TTag>>,
    state: AutocompleteState<Tag<TTag>>,
  }): AutocompleteSource<Tag<TTag>> | undefined
  ```

  A function to transform the returned tags source.

  ```js Example icon=code theme={"system"}
  const tagsPlugin = createTagsPlugin({
    transformSource({ source }) {
      return {
        ...source,
        templates: {
          ...source.templates,
          item({ item }) {
            return `${item.label} in ${item.type}`;
          },
        },
      };
    },
  });
  ```
</ParamField>

<ParamField body="onChange" type="(params: OnChangeParams<TTag>): void">
  ```ts TypeScript icon=code theme={"system"}
  type OnChangeParams<TTag> = PluginSubscribeParams<any> & {
    prevTags: Array<Tag<TTag>>;
    tags: Array<Tag<TTag>>;
  };
  ```

  The function called when the list of tags changes.
  This is useful to customize the behavior of Autocomplete when such an event occurs,
  or integrate with third-party code.
</ParamField>

## Returns

### `data`

<ParamField body="tags" type="Tag<TTag>[]">
  ```ts TypeScript icon=code theme={"system"}
  type Tag<TTag> = BaseTag<TTag> & { remove(): void };
  ```

  Returns the current list of tags.

  If you're not using the default tags source returned by the plugin,
  you can use this to display tags anywhere in your autocomplete.
</ParamField>

<ParamField body="addTags" type="(tags: BaseTag<TTag>[]): void">
  Adds tags to the list.

  The only required property is a `label`.
  You can pass any other property you want, except for `remove`, which is reserved.

  ```js JavaScript icon=code theme={"system"}
  tagsPlugin.data.addTags([{ label: "Apple", facet: "brand" }]);
  ```
</ParamField>

<ParamField body="setTags" type="(tags: BaseTag<TTag>[]): void">
  Sets the list of tags.

  This is helpful to replace the current list.

  ```js JavaScript icon=code theme={"system"}
  tagsPlugin.data.setTags([{ label: "Apple", facet: "brand" }]);
  ```

  To remove some of the tags,
  you can retrieve the current tags list using [`tags`](#param-tags) and filter it to build a list of tags to keep.

  ```js JavaScript icon=code theme={"system"}
  // Filters out all tags with `facet` "brand"
  const newTags = tagsPlugin.data.tags.filter((tag) => tag.facet !== "brand");

  tagsPlugin.data.setTags(newTags);
  ```
</ParamField>
