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

Import

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

About this widget

Use the frequentlyBoughtTogether widget to display a list of frequently bought together items. See also: Set up Algolia Recommend

Examples

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

frequentlyBoughtTogether({
  container: "#frequentlyBoughtTogether",
  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.
frequentlyBoughtTogether({
  // ...
  container: '#frequentlyBoughtTogether',
});
objectIDs
string[]
required
The list of objectIDs 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 array ["A", "B", "C"], you’ll consume three requests from your quota, not one.
JavaScript
frequentlyBoughtTogether({
  // ...
  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
frequentlyBoughtTogether({
  // ...
  limit: 4,
});
threshold
number
The threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned.
JavaScript
frequentlyBoughtTogether({
  // ...
  threshold: 80,
});
queryParameters
Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>
List of search parameters to send.
JavaScript
frequentlyBoughtTogether({
  // ...
  queryParameters: {
    filters: "category:Book",
  },
});
escapeHTML
boolean
default:true
Escapes HTML entities from recommendations string values.
JavaScript
frequentlyBoughtTogether({
  // ...
  escapeHTML: false,
});
templates
object
The templates to use for the widget.
JavaScript
frequentlyBoughtTogether({
  // ...
  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
frequentlyBoughtTogether({
  // ...
  cssClasses: {
    root: "MyCustomFrequentlyBoughtTogether",
    list: [
      "MyCustomFrequentlyBoughtTogether",
      "MyCustomFrequentlyBoughtTogether--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
frequentlyBoughtTogether({
  // ...
  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.
frequentlyBoughtTogether({
  // ...
  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.
frequentlyBoughtTogether({
  // ...
  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.
frequentlyBoughtTogether({
  // ...
  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;

frequentlyBoughtTogether({
  // ...
  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-FrequentlyBoughtTogether">
  <h3 class="ais-FrequentlyBoughtTogether-title">Frequently Bought Together</h3>
  <div class="ais-FrequentlyBoughtTogether-container">
    <ol class="ais-FrequentlyBoughtTogether-list">
      <li class="ais-FrequentlyBoughtTogether-item">...</li>
      <li class="ais-FrequentlyBoughtTogether-item">...</li>
      <li class="ais-FrequentlyBoughtTogether-item">...</li>
    </ol>
  </div>
</section>

Customize the UI with connectFrequentlyBoughtTogether

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

// 2. Create the custom widget
const customFrequentlyBoughtTogether = connectFrequentlyBoughtTogether(
  renderFrequentlyBoughtTogether
);

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

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

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

// ...

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

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 customFrequentlyBoughtTogether = connectFrequentlyBoughtTogether(
  renderFrequentlyBoughtTogether
);

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

Instance options

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
customFrequentlyBoughtTogether({
  // ...
  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
customFrequentlyBoughtTogether({
  // ...
  limit: 4,
});
threshold
number
The threshold for the recommendations confidence score (between 0 and 100). Only recommendations with a greater score are returned.
JavaScript
customFrequentlyBoughtTogether({
  // ...
  threshold: 80,
});
queryParameters
Omit<SearchParameters, 'page' | 'hitsPerPage' | 'offset' | 'length'>
List of search parameters to send.
JavaScript
customFrequentlyBoughtTogether({
  // ...
  queryParameters: {
    filters: "category:Book",
  },
});
escapeHTML
boolean
default:true
Escapes HTML entities from recommendations string values.
JavaScript
customFrequentlyBoughtTogether({
  // ...
  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
customFrequentlyBoughtTogether({
  // ...
  transformItems(items) {
    return items.map((item) => ({
      ...item,
      name: item.name.toUpperCase(),
    }));
  },
});

Full example

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