UI libraries / Recommend / API reference / recommend-react

Recommend context provider

The <Recommend /> context provider lets you batch recommend queries in a single API request

Installation

The Recommend React package is available on the npm registry.

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

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

1
2
3
4
<script src="https://cdn.jsdelivr.net/npm/@algolia/recommend-react"></script>
<script>
  const { FrequentlyBoughtTogether, Recommend, RelatedProducts, TrendingItems, TrendingFacets } = window['@algolia/recommend-react'];
</script>

Usage

You can automatically batch recommend queries in a single API request, by wrapping the Recommend UI components under the Recommend context provider

You can also 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
23
24
25
26
27
28
29
30
31
32
import { FrequentlyBoughtTogether, RelatedProducts, Recommend } from '@algolia/recommend-react';
import recommend from '@algolia/recommend';

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

function Product({ item }) {
  return (
    <pre>
      <code>{JSON.stringify(item)}</code>
    </pre>
  );
}

function App({ currentObjectID }) {
  // ...

  return (
    <Recommend recommendClient={recommendClient} >
      <RelatedProducts
        indexName={indexName}
        objectIDs={[currentObjectID]}
        itemComponent={Product}
      />
      <FrequentlyBoughtTogether
        indexName={indexName}
        objectIDs={[currentObjectID]}
        itemComponent={Product}
      />
    </Recommend>
  );
}

Parameters

Parameter Description
recommendClient
type: RecommendClient
Required

The initialized Algolia Recommend client.

children
type: (props: ChildrenProps) => JSX.Element

A render function to customize what’s displayed within the Recommend context provider. Use it to wrap the Recommend UI components that consume the values from the Recommend context provider.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function App(props) {
  return (
    <Recommend recommendClient={recommendClient}>
      <RelatedProducts
        indexName={indexName}
        objectIDs={[currentObjectID]}
        itemComponent={Product}
      />
      <FrequentlyBoughtTogether
        indexName={indexName}
        objectIDs={[currentObjectID]}
        itemComponent={Product}
      />
    </Recommend>
  );
}
Did you find this page helpful?