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

# trendingFacets

> Shows a list of trending facet values.

<Note>
  If you're using the deprecated [`recommend-js`](https://algolia.com/old-docs/deprecated/recommend/api-reference/recommend-js) UI library,
  see [`trendingFacets`](https://algolia.com/old-docs/deprecated/recommend/api-reference/recommend-js/trendingFacets).
</Note>

```ts Signature theme={"system"}
trendingFacets({
  container: string | HTMLElement,
  facetName: string,
  // Optional parameters
  limit?: number,
  threshold?: number,
  fallbackParameters?: object,
  escapeHTML?: boolean,
  templates?: object,
  cssClasses?: object,
  transformItems?: function,
});
```

## Import

<CodeGroup>
  ```js Package manager theme={"system"}
  import { trendingFacets } from 'instantsearch.js/es/widgets';
  ```

  ```js CDN theme={"system"}
  const { trendingFacets } = instantsearch.widgets;
  // or directly use instantsearch.widgets.trendingFacets()
  ```
</CodeGroup>

## About this widget

Use the `trendingFacets` widget to display a list of trending facet values.

See also: [Set up Algolia Recommend](/doc/guides/algolia-recommend/how-to/set-up)

## Examples

```js JavaScript icon=code theme={"system"}
trendingFacets({
  container: "#trendingFacets",
  facetName: "brand",
  templates: {
    item(item, { html }) {
      return html`<span>${item.facetValue}</span>`;
    },
  },
});
```

## Options

<ParamField body="container" type="string | HTMLElement" required>
  The CSS Selector or `HTMLElement` to insert the widget into.

  <CodeGroup>
    ```js string theme={"system"}
    trendingFacets({
      // ...
      container: '#trendingFacets',
    });
    ```

    ```js HTMLElement theme={"system"}
    trendingFacets({
      container: document.querySelector("#trendingFacets"),
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="facetName" type="string" required>
  The facet attribute to get trending values for.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    facetName: "brand",
  });
  ```
</ParamField>

<ParamField body="limit" type="number">
  The number of trending facet values to retrieve.
  Depending on the available recommendations and the other request parameters,
  the actual number of items may be lower than that.
  If `limit` isn't provided or set to 0, all matching recommendations are returned.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    limit: 4,
  });
  ```
</ParamField>

<ParamField body="threshold" type="number">
  The threshold for the recommendations confidence score (between 0 and 100).
  Only recommendations with a greater score are returned.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    threshold: 80,
  });
  ```
</ParamField>

<ParamField body="fallbackParameters" type="Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>">
  List of [search parameters](/doc/api-reference/search-api-parameters) to send when there aren't enough recommendations.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    fallbackParameters: {
      filters: "category:Book",
    },
  });
  ```
</ParamField>

<ParamField body="escapeHTML" type="boolean" default={true}>
  Escapes HTML entities from recommendations string values.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    escapeHTML: false,
  });
  ```
</ParamField>

<ParamField body="templates" type="object">
  The [templates](#templates) to use for the widget.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    templates: {
      // ...
    },
  });
  ```
</ParamField>

<ParamField body="cssClasses" type="object" default="{}">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#style-your-widgets):

  * `root`. The widget's root element.
  * `emptyRoot`. The container element without results.
  * `title`. The widget's title element.
  * `container`. The container of the list element.
  * `list`. The list of trending facet values.
  * `item`. The list item.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    cssClasses: {
      root: "MyCustomTrendingFacets",
      list: ["MyCustomTrendingFacets", "MyCustomTrendingFacets--subclass"],
    },
  });
  ```
</ParamField>

<ParamField body="transformItems" type="function" default="items => items">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  ```js JavaScript icon=code theme={"system"}
  trendingFacets({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        facetValue: item.facetValue.toUpperCase(),
      }));
    },
  });
  ```
</ParamField>

## Templates

You can customize parts of a widget’s UI using the Templates API.

Each template includes an `html` function,
which you can use as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates).
This function safely renders templates as HTML strings and works directly in the browser—no build step required.
For details, see [Templating your UI](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js/#templating-your-ui).

<Note>
  The `html` function is available in InstantSearch.js version 4.46.0 or later.
</Note>

<ParamField body="empty" type="string | function">
  The template to use when there are no trending facet values.

  <CodeGroup>
    ```js function theme={"system"}
    trendingFacets({
      // ...
      templates: {
        empty(_, { html }) {
          return html`<p>No trending facets.</p>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    trendingFacets({
      // ...
      templates: {
        empty: "No trending facets.",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="header" type="string | function">
  The template to use for the widget header.
  This template receives the items as well as the `cssClasses` object.

  <CodeGroup>
    ```js function theme={"system"}
    trendingFacets({
      // ...
      templates: {
        header({ cssClasses, items }, { html }) {
          return html`<h2 class=${cssClasses.title}>
            Trending (${items.length})
          </h2>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    trendingFacets({
      // ...
      templates: {
        header: "<h2>Trending ({{items.length}})</h2>",
      },
    });
    ```
  </CodeGroup>
</ParamField>

<ParamField body="item" type="string | function">
  The template to use for each trending facet value.
  This template receives an object with `facetName`, `facetValue`, and `_score`.

  <CodeGroup>
    ```js function theme={"system"}
    trendingFacets({
      // ...
      templates: {
        item(item, { html }) {
          return html`<span>${item.facetValue}</span>`;
        },
      },
    });
    ```

    ```js string theme={"system"}
    // String-based templates are deprecated, use functions instead.
    trendingFacets({
      // ...
      templates: {
        item: `{{ facetValue }}`,
      },
    });
    ```
  </CodeGroup>
</ParamField>

## HTML output

```html HTML icon=code-xml theme={"system"}
<section class="ais-TrendingFacets">
  <h3 class="ais-TrendingFacets-title">Trending</h3>
  <div class="ais-TrendingFacets-container">
    <ol class="ais-TrendingFacets-list">
      <li class="ais-TrendingFacets-item">...</li>
      <li class="ais-TrendingFacets-item">...</li>
      <li class="ais-TrendingFacets-item">...</li>
    </ol>
  </div>
</section>
```

## Customize the UI with `connectTrendingFacets`

If you want to create your own UI of the `trendingFacets` widget, you can use connectors.

To use `connectTrendingFacets`, you can import it with the declaration relevant to how you installed InstantSearch.js.

<CodeGroup>
  ```js Package manager theme={"system"}
  import { connectTrendingFacets } from 'instantsearch.js/es/connectors';
  ```

  ```js CDN theme={"system"}
  const { connectTrendingFacets } = instantsearch.connectors;
  // or directly use instantsearch.connectors.connectTrendingFacets()
  ```
</CodeGroup>

Then it's a 3-step process:

```js JavaScript icon=code theme={"system"}
// 1. Create a render function
const renderTrendingFacets = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customTrendingFacets = connectTrendingFacets(renderTrendingFacets);

// 3. Instantiate
search.addWidgets([
  customTrendingFacets({
    // instance params
  }),
]);
```

### Create a render function

This rendering function is called before the first search (`init` lifecycle step)
and each time results come back from Algolia (`render` lifecycle step).

```js JavaScript icon=code theme={"system"}
const renderTrendingFacets = (renderOptions, isFirstRender) => {
  const { items, widgetParams } = renderOptions;

  if (isFirstRender) {
    // Do some initial rendering and bind events
  }

  // Render the widget
};
```

#### Rendering options

<ParamField body="items" type="object[]">
  The trending facet values from the Algolia Recommend API.
  Each item has `facetName`, `facetValue`, and `_score` properties.

  ```js JavaScript icon=code theme={"system"}
  const renderTrendingFacets = (renderOptions, isFirstRender) => {
    const { items } = renderOptions;

    document.querySelector('#trendingFacets').innerHTML = `
      <ul>
        ${items
          .map(item => `<li>${item.facetValue}</li>`)
          .join('')}
      </ul>
    `;
  };
  ```
</ParamField>

<ParamField body="widgetParams" type="object">
  All original widget options forwarded to the render function.

  ```js JavaScript icon=code theme={"system"}
  const renderTrendingFacets = (renderOptions, isFirstRender) => {
    const { widgetParams } = renderOptions;

    widgetParams.container.innerHTML = '...';
  };

  // ...

  search.addWidgets([
    customTrendingFacets({
      // ...
      container: document.querySelector('#trendingFacets'),
    })
  ]);
  ```
</ParamField>

### Create and instantiate the custom widget

First, create your custom widgets using a rendering function.
Then, instantiate them with parameters.

There are two kinds of parameters you can pass:

* **Instance parameters**. Predefined options that configure Algolia's behavior.
* **Custom parameters**. Parameters you define to make the widget reusable and adaptable.

Inside the `renderFunction`, both instance and custom parameters are accessible through `connector.widgetParams`.

```js JavaScript icon=code theme={"system"}
const customTrendingFacets = connectTrendingFacets(
  renderTrendingFacets
);

search.addWidgets([
  customTrendingFacets({
    // Required parameter
    facetName: string,
    // Optional parameters
    limit: number,
    threshold: number,
    fallbackParameters: object,
    escapeHTML: boolean,
    transformItems: function,
  })
]);
```

#### Instance options

<ParamField body="facetName" type="string" required>
  The facet attribute to get trending values for.

  ```js JavaScript icon=code theme={"system"}
  customTrendingFacets({
    // ...
    facetName: "brand",
  });
  ```
</ParamField>

<ParamField body="limit" type="number">
  The number of trending facet values to retrieve.
  Depending on the available recommendations and the other request parameters,
  the actual number of items may be lower than that.
  If `limit` isn't provided or set to 0, all matching recommendations are returned.

  ```js JavaScript icon=code theme={"system"}
  customTrendingFacets({
    // ...
    limit: 4,
  });
  ```
</ParamField>

<ParamField body="threshold" type="number">
  The threshold for the recommendations confidence score (between 0 and 100).
  Only recommendations with a greater score are returned.

  ```js JavaScript icon=code theme={"system"}
  customTrendingFacets({
    // ...
    threshold: 80,
  });
  ```
</ParamField>

<ParamField body="fallbackParameters" type="Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>">
  List of [search parameters](/doc/api-reference/search-api-parameters) to send when there aren't enough recommendations.

  ```js JavaScript icon=code theme={"system"}
  customTrendingFacets({
    // ...
    fallbackParameters: {
      filters: "category:Book",
    },
  });
  ```
</ParamField>

<ParamField body="escapeHTML" type="boolean" default={true}>
  Escapes HTML entities from recommendations string values.

  ```js JavaScript icon=code theme={"system"}
  customTrendingFacets({
    // ...
    escapeHTML: false,
  });
  ```
</ParamField>

<ParamField body="transformItems" type="function" default="items => items">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  ```js JavaScript icon=code theme={"system"}
  customTrendingFacets({
    // ...
    transformItems(items) {
      return items.map((item) => ({
        ...item,
        facetValue: item.facetValue.toUpperCase(),
      }));
    },
  });
  ```
</ParamField>

### Full example

<CodeGroup>
  ```html HTML theme={"system"}
  <div id="trendingFacets"></div>
  ```

  ```js JavaScript theme={"system"}
  // Create the render function
  const renderTrendingFacets = (renderOptions, isFirstRender) => {
    const { items, widgetParams } = renderOptions;

    widgetParams.container.innerHTML = `
      <ul>
        ${items
          .map(item => `<li>${item.facetValue}</li>`)
          .join('')}
      </ul>
    `;
  };

  // Create the custom widget
  const customTrendingFacets = connectTrendingFacets(
    renderTrendingFacets
  );

  // Instantiate the custom widget
  search.addWidgets([
    customTrendingFacets({
      container: document.querySelector('#trendingFacets'),
      facetName: 'brand',
    })
  ]);
  ```
</CodeGroup>
