UI libraries / Autocomplete / API reference / autocomplete-plugin-tags

This plugin lets you manage and display tags in Autocomplete. You can use tags in various ways, such as displaying filters or representing navigation steps.

Install the plugin

1
2
3
yarn add @algolia/autocomplete-plugin-tags
# or
npm install @algolia/autocomplete-plugin-tags

Import the plugin into your project

1
2
3
4
5
6
7
8
9
10
import { autocomplete } from '@algolia/autocomplete-js';
import { createTagsPlugin } from '@algolia/autocomplete-plugin-tags';

const tagsPlugin = createTagsPlugin();

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

The plugin includes an autocomplete-theme-classic-compatible theme.

1
import '@algolia/autocomplete-plugin-tags/dist/theme.min.css';

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

1
2
3
4
5
6
7
8
9
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-tags/dist/theme.min.css"
/>

<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-tags"></script>
<script>
  const { createTagsPlugin } = window['@algolia/autocomplete-plugin-tags'];
</script>

Initialize the plugin with initialTags

The plugin lets you pass initialTags 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.

1
2
3
4
5
6
// 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.

If you want to display tags manually, for example, with the render function or in the search box, you can prevent the plugin from returning a source. The plugin exposes an API on the Context to let you access tags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// ...
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
    );
  },
});

Returned tags expose a remove function for removing individual tags.

The plugin also exposes an addTags and a setTags function on the Context to update the list of tags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ...

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
    );
  },
});

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.

1
2
3
document.getElementById('#clear-speakers').addEventListener('click', () => {
  tagsPlugin.data.setTags([]);
});

Parameters

Parameter Description
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.

1
type BaseTag<TTag = Record<string, unknown>> = TTag & { label: string };
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const tagsPlugin = createTagsPlugin({
  getTagsSubscribers() {
    return [
      {
        sourceId: 'brands',
        getTag({ item }) {
          return {
            ...item,
            label: item.name,
          };
        },
      },
    ];
  },
});
transformSource
type: (params: { source: AutocompleteSource<Tag<TTag>>, state: AutocompleteState<Tag<TTag>> }): AutocompleteSource<Tag<TTag>> | undefined

A function to transform the returned tags source.

1
2
3
4
5
6
7
8
9
10
11
12
13
const tagsPlugin = createTagsPlugin({
  transformSource({ source }) {
    return {
      ...source,
      templates: {
        ...source.templates,
        item({ item }) {
          return `${item.label} in ${item.type}`;
        },
      },
    };
  },
});

To avoid rendering tags as a source, you can return undefined.

1
2
3
4
5
const tagsPlugin = createTagsPlugin({
  transformSource() {
    return undefined;
  },
});
onChange
type: (params: OnChangeParams<TTag>): void

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.

1
2
3
4
type OnChangeParams<TTag> = PluginSubscribeParams<any> & {
  prevTags: Array<Tag<TTag>>;
  tags: Array<Tag<TTag>>;
};

Returns

data

Parameter Description
tags
type: Tag<TTag>[]

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.

1
type Tag<TTag> = BaseTag<TTag> & { remove(): void };
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.

1
tagsPlugin.data.addTags([{ label: 'Apple', facet: 'brand' }]);
setTags
type: (tags: BaseTag<TTag>[]): void

Sets the list of tags.

This is helpful to replace the current list.

1
tagsPlugin.data.setTags([{ label: 'Apple', facet: 'brand' }]);

To remove some of the tags, you can retrieve the current tags list using tags and filter it to build a list of tags to keep.

1
2
3
4
// Filters out all tags with `facet` "brand"
const newTags = tagsPlugin.data.tags.filter((tag) => tag.facet !== 'brand');

tagsPlugin.data.setTags(newTags);
Did you find this page helpful?