Skip to main content
If you’re using the deprecated recommend-js UI library, see relatedProducts.
Signature
relatedProducts({
  container: string | HTMLElement,
  objectIDs: string[],
  // Optional parameters
  limit?: number,
  threshold?: number,
  queryParameters?: object,
  fallbackParameters?: object,
  escapeHTML?: boolean,
  templates?: object,
  cssClasses?: object,
  transformItems?: function,
});

Import

import { relatedProducts } from 'instantsearch.js/es/widgets';

About this widget

Use the relatedProducts widget to display a list of related products and related content. See also: Set up Algolia Recommend

Examples

JavaScript
relatedProducts({
  container: "#relatedProducts",
  objectIDs: ["5723537"],
  templates: {
    item(recommendation, { html }) {
      return html`
        <h2>${recommendation.name}</h2>
        <p>${recommendation.description}</p>
      `;
    },
  },
});
Display the relatedProducts widget as a scrollable carousel.
JavaScript
import { carousel } from "instantsearch.js/es/templates";
// or
const { carousel } = instantsearch.templates;

relatedProducts({
  container: "#relatedProducts",
  objectIDs: ["5723537"],
  templates: {
    item(recommendation, { html }) {
      return html`
        <h2>${recommendation.name}</h2>
        <p>${recommendation.description}</p>
      `;
    },
    layout: carousel(),
  },
});

Options

container
string | HTMLElement
required
The CSS Selector or HTMLElement to insert the widget into.
relatedProducts({
  // ...
  container: '#relatedProducts',
});
objectIDs
string[]
required
The list of object IDs for which to get recommendations. If you specify multiple object IDs, 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 array ["A", "B", "C"], you’ll consume three requests from your quota, not one.
JavaScript
relatedProducts({
  // ...
  objectIDs: ["1", "2", "3"],
});
limit
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.
JavaScript
relatedProducts({
  // ...
  limit: 4,
});
threshold
number
The threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned.
JavaScript
relatedProducts({
  // ...
  threshold: 80,
});
queryParameters
Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>
List of search parameters to send, except page, hitsPerPage, offset, and length.
JavaScript
relatedProducts({
  // ...
  queryParameters: {
    filters: "category:Book",
  },
});
fallbackParameters
Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>
List of search parameters to send as additional filters when there aren’t enough recommendations.
JavaScript
relatedProducts({
  // ...
  fallbackParameters: {
    filters: "category:Book",
  },
});
escapeHTML
boolean
default:true
Escapes HTML entities from recommendations string values.
JavaScript
relatedProducts({
  // ...
  escapeHTML: false,
});
templates
object
The templates to use for the widget.
JavaScript
relatedProducts({
  // ...
  templates: {
    // ...
  },
});
cssClasses
object
default:"{}"
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.
JavaScript
relatedProducts({
  // ...
  cssClasses: {
    root: "MyCustomRelatedProducts",
    list: ["MyCustomRelatedProducts", "MyCustomRelatedProducts--subclass"],
  },
});
transformItems
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 and parameters from the helper, such as disjunctiveFacetsRefinements.
JavaScript
relatedProducts({
  // ...
  transformItems(items) {
    return items.map((item) => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

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. This function safely renders templates as HTML strings and works directly in the browser—no build step required. For details, see Templating your UI.
The html function is available in InstantSearch.js version 4.46.0 or later.
empty
string | function
The template to use when there are no recommendations.
relatedProducts({
  // ...
  templates: {
    empty(_, { html }) {
      return html`<p>No recommendations.</p>`;
    },
  },
});
header
string | function
The template to use for the recommendations header. This template receives the recommendations as well as the cssClasses object.
relatedProducts({
  // ...
  templates: {
    header({ cssClasses, items }, { html }) {
      return html`<h2 class=${cssClasses.title}>
        Recommendations (${items.length})
      </h2>`;
    },
  },
});
item
string | function
The template to use for each recommendation. This template receives an object containing a single record.
relatedProducts({
  // ...
  templates: {
    item(recommendation, { html }) {
      return html`
        <h2>${recommendation.name}</h2>
        <p>${recommendation.description}</p>
      `;
    },
  },
});
layout
function
since: v4.74.0
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.
import { carousel } from 'instantsearch.js/es/templates';
// or
const { carousel } = instantsearch.templates;

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

HTML output

HTML
<section class="ais-RelatedProducts">
  <h3 class="ais-RelatedProducts-title">Related Products</h3>
  <div class="ais-RelatedProducts-container">
    <ol class="ais-RelatedProducts-list">
      <li class="ais-RelatedProducts-item">...</li>
      <li class="ais-RelatedProducts-item">...</li>
      <li class="ais-RelatedProducts-item">...</li>
    </ol>
  </div>
</section>

Customize the UI with connectRelatedProducts

If you want to create your own UI of the relatedProducts widget, you can use connectors. To use connectRelatedProducts, you can import it with the declaration relevant to how you installed InstantSearch.js.
import { connectRelatedProducts } from "instantsearch.js/es/connectors";
Then it’s a 3-step process:
JavaScript
// 1. Create a render function
const renderRelatedProducts = (renderOptions, isFirstRender) => {
  // Rendering logic
};

// 2. Create the custom widget
const customRelatedProducts = connectRelatedProducts(renderRelatedProducts);

// 3. Instantiate
search.addWidgets([
  customRelatedProducts({
    // 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).
JavaScript
const renderRelatedProducts = (renderOptions, isFirstRender) => {
  const { items, widgetParams } = renderOptions;

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

  // Render the widget
};

Rendering options

items
object[]
The matched recommendations from the Algolia API.
JavaScript
const renderRelatedProducts = (renderOptions, isFirstRender) => {
  const { items } = renderOptions;

  document.querySelector('#relatedProducts').innerHTML = `
    <ul>
      ${items
        .map(item => `<li>${item.name}</li>`)
        .join('')}
    </ul>
  `;
};
widgetParams
object
All original widget options forwarded to the render function.
JavaScript
const renderRelatedProducts = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

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

// ...

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

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.
JavaScript
const customRelatedProducts = connectRelatedProducts(
  renderRelatedProducts
);

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

Instance options

objectIDs
string[]
required
The list of object IDs to get recommendations for. If you specify multiple object IDs, 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 array ["A", "B", "C"], you’ll consume three requests from your quota, not one.
JavaScript
customRelatedProducts({
  // ...
  objectIDs: ["1", "2", "3"],
});
limit
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.
JavaScript
customRelatedProducts({
  // ...
  limit: 4,
});
threshold
number
The threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned.
JavaScript
customRelatedProducts({
  // ...
  threshold: 80,
});
queryParameters
Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>
List of search parameters to send.
JavaScript
customRelatedProducts({
  // ...
  queryParameters: {
    filters: "category:Book",
  },
});
fallbackParameters
Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>
List of search parameters to send as additional filters when there aren’t enough recommendations.
JavaScript
customRelatedProducts({
  // ...
  fallbackParameters: {
    filters: "category:Book",
  },
});
escapeHTML
boolean
default:true
Escapes HTML entities from recommendations string values.
JavaScript
customRelatedProducts({
  // ...
  escapeHTML: false,
});
transformItems
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 and parameters from the helper, such as disjunctiveFacetsRefinements.
JavaScript
customRelatedProducts({
  // ...
  transformItems(items) {
    return items.map((item) => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

Full example

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