🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / Recommend / API reference / recommend-js

The relatedProducts function lets you render Related Products and Related Content.

Installation

The Recommend JavaScript package is available on the npm registry.

1
2
3
yarn add @algolia/recommend-js
# or
npm install @algolia/recommend-js

If you don’t want to use a package manager, you can use a standalone endpoint:

1
2
3
4
5
6
<script src="https://cdn.jsdelivr.net/npm/@algolia/recommend-js"></script>
<script src="https://cdn.jsdelivr.net/npm/@algolia/recommend"></script>
<script>
  const { frequentlyBoughtTogether, relatedProducts, trendingItems, trendingFacets } = window['@algolia/recommend-js'];
  const recommend = window['@algolia/recommend'];
</script>

Usage

To get started, you need to specify a container to inject the component into.

1
<div id="relatedProducts"></div>

Then, you can call the relatedProducts function and provide the container. It can be a CSS selector or an Element.

You can customize how to render each item by passing a custom component to the itemComponent prop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/** @jsx h */
import { h } from 'preact';
import { relatedProducts } from '@algolia/recommend-js';
import recommend from '@algolia/recommend';

const recommendClient = recommend('YourApplicationID', 'YourSearchOnlyAPIKey');
const indexName = 'YOUR_INDEX_NAME';
const currentObjectID = 'YOUR_OBJECT_ID';

relatedProducts({
  container: '#relatedProducts',
  recommendClient,
  indexName,
  objectIDs: [currentObjectID],
  itemComponent({ item }) {
    return (
      <pre>
        <code>{JSON.stringify(item)}</code>
      </pre>
    );
  },
});

Horizontal slider view

You can also wrap the component within a custom view. For example, you can use the provided HorizontalSlider UI component to display items as a scrollable slider.

The horizontalSlider UI component is currently not supported with recommend-js when imported as a UMD bundle, only when using a package manager.

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
/** @jsx h */
import { h } from 'preact';
import { relatedProducts } from '@algolia/recommend-js';
import { horizontalSlider } from '@algolia/ui-components-horizontal-slider-js';
import recommend from '@algolia/recommend';

import '@algolia/ui-components-horizontal-slider-theme';

const recommendClient = recommend('YourApplicationID', 'YourSearchOnlyAPIKey');
const indexName = 'YOUR_INDEX_NAME';
const currentObjectID = 'YOUR_OBJECT_ID';

relatedProducts({
  container: '#relatedProducts',
  recommendClient,
  indexName,
  objectIDs: [currentObjectID],
  view: horizontalSlider,
  itemComponent({ item }) {
    return (
      <pre>
        <code>{JSON.stringify(item)}</code>
      </pre>
    );
  },
});

If you don’t use JSX in your project, you can return tagged templates using htm or leverage createElement and Fragment from itemComponent, headerComponent and fallbackComponent.

With createElement

You can use createElement and Fragment in every component props to create components without JSX. They’re bound to Preact 10’s createElement and Fragment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { relatedProducts } from '@algolia/recommend-js';
import recommend from '@algolia/recommend';

const recommendClient = recommend('YourApplicationID', 'YourSearchOnlyAPIKey');
const indexName = 'YOUR_INDEX_NAME';
const currentObjectID = 'YOUR_OBJECT_ID';

relatedProducts({
  container: '#relatedProducts',
  recommendClient,
  indexName,
  objectIDs: [currentObjectID],
  itemComponent({ item, createElement, Fragment }) {
    return createElement(
      'pre',
      null,
      createElement('code', null, JSON.stringify(item))
    );
  },
});

With html

You can use the exposed html function. This function is bind with htm. It allows to pass templates as HTML strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { relatedProducts } from '@algolia/recommend-js';
import recommend from '@algolia/recommend';

const recommendClient = recommend('YourApplicationID', 'YourSearchOnlyAPIKey');
const indexName = 'YOUR_INDEX_NAME';
const currentObjectID = 'YOUR_OBJECT_ID';

relatedProducts({
  container: '#relatedProducts',
  recommendClient,
  indexName,
  objectIDs: [currentObjectID],
  itemComponent({ item, html }) {
    return html`<pre>
      <code>${JSON.stringify(item)}</code>
    </pre>`;
  },
});

Parameters

Parameter Description
itemComponent
type: ({ item, createElement, Fragment, html }) => JSX.Element | VNode | VNode[]
Required

The function to display each item.

container
type: string | HTMLElement

The container for the component. You can either pass a CSS selector or an Element. If several containers match the selector, it picks the first one.

When undefined, the function returns a JSX element to inject wherever you want.

headerComponent
type: ({ classNames, recommendations, translations, Fragment, createElement, html }) => JSX.Element | VNode | VNode[]

The function to render a header for your items.

The default implementation is:

1
2
3
4
5
6
7
8
9
10
11
12
13
function HeaderComponent(props) {
  return (
    if (!props.translations.title) {
      return null;
    }

    return (
      <h3 className={cx('auc-Recommend-title', props.classNames.title)}>
        {props.translations.title}
      </h3>
    );
  );
}
fallbackComponent
type: ({ createElement, Fragment, html }) => JSX.Element | VNode | VNode[]

A fallback component to render when no recommendations are returned.

view
type: ViewProps

The view component to render your items into. For example, you can use the horizontalSlider UI component.

The horizontalSlider UI component is currently not supported with recommend-js when imported as a UMD bundle, only when using a package manager.

The default implementation is:

1
2
3
4
5
6
7
8
9
10
11
12
13
function ListView(props) {
  return (
    <div className="auc-Recommend-container">
      <ol className="auc-Recommend-list">
        {props.items.map(item => (
          <li key={item.objectID} className="auc-Recommend-item">
            <props.itemComponent item={item} />
          </li>
        ))}
      </ol>
    </div>
  );
}
environment
type: typeof window
default: window

The environment in which your application is running. This is useful when using Recommend in a different context than window.

Parameter Description
classNames
type: RelatedProductsClassNames

The class names for the component.

1
2
3
4
5
6
7
type RelatedProductsClassNames = Partial<{
  root: string;
  title: string;
  container: string;
  list: string;
  item: string;
}>;
translations
type: RelatedProductTranslations

The translations for the component.

1
2
3
4
type RelatedProductTranslations = Partial<{
  title: string;
  showMore: string;
}>;

This function also accepts all the props that useRelatedProducts supports:

Parameter Description
recommendClient
type: RecommendClient
Required

The initialized Algolia Recommend client.

indexName
type: string
Required

The name of the target index.

objectIDs
type: string[]
Required

An array of objectIDs of the items to get recommendations for.

If you specify multiple objectIDs, you’ll get a single set of aggregated results from the requests, ordered by their score.

Each objectID you pass in the array counts towards the number of requests in your pricing plan. For example, if you want recommendations for the objectID array [ “A”,”B”,”C”], you’ll consume three requests from your quota, not one.

maxRecommendations
type: number

The number of recommendations to retrieve. Depending on the available recommendations and the other request parameters, the actual number of hits may be lower than that. If maxRecommendations isn’t provided or set to 0, all matching recommendations are returned, and no fallback request is performed.

threshold
type: number

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

fallbackParameters
type: Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>

List of search parameters to send.

Additional filters to use as fallback when there aren’t enough recommendations.

queryParameters
type: Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>

List of search parameters to send.

transformItems
type: (items: Array<RecordWithObjectID<TItem>>) => items

A function to transform the retrieved items before passing them to the component. It’s useful when adding, removing, changing, or reordering items.

Did you find this page helpful?