UI libraries / InstantSearch.js / Widgets
Signature
trendingItems({
  container: string|HTMLElement,
  // Optional parameters
  facetName: string,
  facetValue: string,
  limit: number,
  threshold: number,
  queryParameters: object,
  fallbackParameters: object,
  escapeHTML: boolean,
  templates: object,
  cssClasses: object,
  transformItems: function,
});
Import
1
import { trendingItems } from 'instantsearch.js/es/widgets';

About this widget

Use the trendingItems widget to display a list of trending items.

If you’re using the deprecated recommend-js UI library, please refer to the API reference for the trendingItems function.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
trendingItems({
  container: '#trendingItems',
  facetName: 'category',
  facetValue: 'Book',
  templates: {
    item(recommendation, { html }) {
      return html`
        <h2>${recommendation.name}</h2>
        <p>${recommendation.description}</p>
      `;
    },
  },
});

Display the trendingItems widget as a scrollable carousel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { carousel } from 'instantsearch.js/es/templates';
// or
const { carousel } = instantsearch.templates;

trendingItems({
  container: '#trendingItems',
  facetName: 'category',
  facetValue: 'Book',
  templates: {
    item(recommendation, { html }) {
      return html`
        <h2>${recommendation.name}</h2>
        <p>${recommendation.description}</p>
      `;
    },
    layout: carousel(),
  },
});

Options

container
type: string|HTMLElement
Required

The CSS Selector or HTMLElement to insert the widget into.

1
2
3
4
trendingItems({
  // ...
  container: '#trendingItems',
});
facetName
type: string
Optional

The facet attribute to get recommendations for. This parameter should be used along with facetValue.

1
2
3
4
5
trendingItems({
  // ...
  facetName: 'category',
  facetValue: 'Book',
});
facetValue
type: string
Optional

The value for the targeted facet name. This parameter should be used along with facetName.

1
2
3
4
5
trendingItems({
  // ...
  facetName: 'category',
  facetValue: 'Book',
});
limit
type: number

The number of recommendations 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.

1
2
3
4
trendingItems({
  // ...
  limit: 4,
});
threshold
type: number

The threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned.

1
2
3
4
trendingItems({
  // ...
  threshold: 80,
});
queryParameters
type: Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>

List of search parameters to send.

1
2
3
4
5
6
trendingItems({
  // ...
  queryParameters: {
    filters: 'category:Book',
  },
});
fallbackParameters
type: Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>

List of search parameters to send as additional filters when there aren’t enough recommendations.

1
2
3
4
5
6
trendingItems({
  // ...
  fallbackParameters: {
    filters: 'category:Book',
  },
});
escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from recommendations string values.

1
2
3
4
trendingItems({
  // ...
  escapeHTML: false,
});
templates
type: object
Optional

The templates to use for the widget.

1
2
3
4
5
6
trendingItems({
  // ...
  templates: {
    // ...
  },
});
cssClasses
type: object
default: {}
Optional

The CSS classes you can override:

  • 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 recommendations.
  • item: the list item.
1
2
3
4
5
6
7
8
9
10
trendingItems({
  // ...
  cssClasses: {
    root: 'MyCustomTrendingItems',
    list: [
      'MyCustomTrendingItems',
      'MyCustomTrendingItems--subclass',
    ],
  },
});
transformItems
type: function
default: items => items
Optional

Receives the recommendations and is called before displaying them. It returns a new array with the same “shape” as the original. This is helpful when transforming or reordering items.

The entire results data is also available, including all regular response parameters.

1
2
3
4
5
6
7
8
9
trendingItems({
  // ...
  transformItems(items) {
    return items.map(item => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

Templates

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

Every template provides an html function you can use as a tagged template. Using html lets you safely provide templates as an HTML string. It works directly in the browser without a build step. See Templating your UI for more information.

The html function is available starting from v4.46.0.

empty
type: string|function
Optional

The template to use when there are no recommendations.

1
2
3
4
5
6
7
8
trendingItems({
  // ...
  templates: {
    empty(_, { html }) {
      return html`<p>No recommendations.</p>`;
    },
  },
});
header
type: string|function
Optional

The template to use for the recommendations header. This template receives the recommendations as well as the cssClasses object.

1
2
3
4
5
6
7
8
9
10
trendingItems({
  // ...
  templates: {
    header({ cssClasses, items }, { html }) {
      return html`<h2 class=${cssClasses.title}>
        Recommendations (${items.length})
      </h2>`;
    },
  },
});
item
type: string|function
Optional

The template to use for each recommendation. This template receives an object containing a single record.

1
2
3
4
5
6
7
8
9
10
11
trendingItems({
  // ...
  templates: {
    item(recommendation, { html }) {
      return html`
        <h2>${recommendation.name}</h2>
        <p>${recommendation.description}</p>
      `;
    },
  },
});
layout
since: v4.74.0
type: function
Optional

The template to use to wrap all items.

InstantSearch.js provides an out-of-the-box carousel layout template with the following options:

cssClasses

  • root: the carousel’s root element.
  • list: the list of recommendations.
  • item: the list item.
  • navigation: the navigation controls.
  • navigationPrevious: the “Previous” navigation control.
  • navigationNext: the “Next” navigation control.

templates

  • previous: the content of the “Previous” navigation control.
  • next: the content of the “Next” navigation control.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { carousel } from 'instantsearch.js/es/templates';
// or
const { carousel } = instantsearch.templates;

trendingItems({
  // ...
  templates: {
    layout: carousel({
      cssClasses: {
        root: 'MyCustomCarousel',
      },
      templates: {
        previous({ html }) {
          return html`<p>Previous</p>`;
        },
        next({ html }) {
          return html`<p>Next</p>`;
        },
      },
    }),
  },
});

HTML output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<section class="ais-TrendingItems">
  <h3 class="ais-TrendingItems-title">Trending Items</h3>
  <div class="ais-TrendingItems-container">
    <ol class="ais-TrendingItems-list">
      <li class="ais-TrendingItems-item">
        ...
      </li>
      <li class="ais-TrendingItems-item">
        ...
      </li>
      <li class="ais-TrendingItems-item">
        ...
      </li>
    </ol>
  </div>
</section>

Customize the UI with connectTrendingItems

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

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

1
import { connectTrendingItems } from 'instantsearch.js/es/connectors';

Then it’s a 3-step process:

// 1. Create a render function
const renderTrendingItems = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customTrendingItems = connectTrendingItems(
  renderTrendingItems
);

// 3. Instantiate
search.addWidgets([
  customTrendingItems({
    // 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).

const renderTrendingItems = (renderOptions, isFirstRender) => {
  const {
    object[] items,
    object widgetParams,
  } = renderOptions;

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

  // Render the widget
}

Rendering options

items
type: object[]

The matched recommendations from the Algolia API.

1
2
3
4
5
6
7
8
9
10
11
const renderTrendingItems = (renderOptions, isFirstRender) => {
  const { items } = renderOptions;

  document.querySelector('#trendingItems').innerHTML = `
    <ul>
      ${items
        .map(item => `<li>${item.name}</li>`)
        .join('')}
    </ul>
  `;
};
widgetParams
type: object

All original widget options forwarded to the render function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const renderTrendingItems = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

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

// ...

search.addWidgets([
  customTrendingItems({
    // ...
    container: document.querySelector('#trendingItems'),
  })
]);

Create and instantiate the custom widget

We first create custom widgets from our rendering function, then we instantiate them. When doing that, there are two types of parameters you can give:

  • Instance parameters: they are predefined parameters that you can use to configure the behavior of Algolia.
  • Your own parameters: to make the custom widget generic.

Both instance and custom parameters are available in connector.widgetParams, inside the renderFunction.

const customTrendingItems = connectTrendingItems(
  renderTrendingItems
);

search.addWidgets([
  customTrendingItems({
    // Optional parameters
    facetName: string,
    facetValue: string,
    limit: number,
    threshold: number,
    queryParameters: object,
    fallbackParameters: object,
    escapeHTML: boolean,
    transformItems: function,
  })
]);

Instance options

facetName
type: string
Optional

The facet attribute to get recommendations for. This parameter should be used along with facetValue.

1
2
3
4
5
customTrendingItems({
  // ...
  facetName: 'category',
  facetValue: 'Book',
});
facetValue
type: string
Optional

The value for the targeted facet name. This parameter should be used along with facetName.

1
2
3
4
5
customTrendingItems({
  // ...
  facetName: 'category',
  facetValue: 'Book',
});
limit
type: number

The number of recommendations 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.

1
2
3
4
customTrendingItems({
  // ...
  limit: 4,
});
threshold
type: number

The threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned.

1
2
3
4
customTrendingItems({
  // ...
  threshold: 80,
});
queryParameters
type: Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>

List of search parameters to send.

1
2
3
4
5
6
customTrendingItems({
  // ...
  queryParameters: {
    filters: 'category:Book',
  },
});
fallbackParameters
type: Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>

List of search parameters to send as additional filters when there aren’t enough recommendations.

1
2
3
4
5
6
customTrendingItems({
  // ...
  fallbackParameters: {
    filters: 'category:Book',
  },
});
escapeHTML
type: boolean
default: true
Optional

Escapes HTML entities from recommendations string values.

1
2
3
4
customTrendingItems({
  // ...
  escapeHTML: false,
});
transformItems
type: function
default: items => items
Optional

Receives the recommendations and is called before displaying them. It returns a new array with the same “shape” as the original. This is helpful when transforming or reordering items.

The entire results data is also available, including all regular response parameters.

1
2
3
4
5
6
7
8
9
customTrendingItems({
  // ...
  transformItems(items) {
    return items.map(item => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

Full example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Create the render function
const renderTrendingItems = (renderOptions, isFirstRender) => {
  const { items, widgetParams } = renderOptions;

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

// Create the custom widget
const customTrendingItems = connectTrendingItems(
  renderTrendingItems
);

// Instantiate the custom widget
search.addWidgets([
  customTrendingItems({
    container: document.querySelector('#trendingItems'),
  })
]);
Did you find this page helpful?