🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / InstantSearch.js / Widgets
Signature
stats({
  container: string|HTMLElement,
  // Optional parameters
  templates: object,
  cssClasses: object,
});
Import
1
import { stats } from 'instantsearch.js/es/widgets';

About this widget

The stats widget displays the total number of matching hits and the time it took to get them (time spent in the Algolia server).

Examples

1
2
3
stats({
  container: '#stats',
});

Options

Parameter Description
container
type: string|HTMLElement
Required

The CSS Selector or HTMLElement to insert the widget into.

1
2
3
stats({
  container: '#stats',
});
templates
type: object
Optional

The templates to use for the widget.

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

The CSS classes you can override:

  • root: the root element of the widget.
  • text: the text element.
1
2
3
4
5
6
7
stats({
  // ...
  cssClasses: {
    root: 'MyCustomStats',
    text: ['MyCustomStatsText', 'MyCustomStatsText--subclass'],
  },
});

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.

Parameter Description
text
type: string|function
Optional

The template to use to customize the text. It exposes:

  • hasManyResults: boolean: indicates whether the search has more than one result.
  • hasNoResults: boolean: indicates whether the search has no results.
  • hasOneResult: boolean: indicates whether the search has one result.
  • areHitsSorted: boolean: indicates whether Relevant sort is applied to the result.
  • nbSortedHits: number: the number of sorted hits from Relevant sort.
  • hasManySortedResults: boolean: indicates whether the search has more than one sorted result.
  • hasNoSortedResults: boolean: indicates whether the search has no sorted results.
  • hasOneSortedResults: boolean: indicates whether the search has one sorted result.
  • hitsPerPage: number: maximum number of hits returned per page.
  • nbHits: number: the number of hits matched by the query.
  • nbPages: number: the number of returned pages. Calculation is based on the total number of hits (nbHits) divided by the number of hits per page (hitsPerPage), rounded up to the nearest integer.
  • page: number: the position of the current page (zero-based).
  • processingTimeMS: number: the time the server took to process the request, in milliseconds. This doesn’t include network time.
  • query: string: the query sent to the server.
  • cssClasses: object: same option as the cssClasses parameter provided to the widget.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
stats({
  // ...
  templates: {
    text(data, { html }) {
      let count = '';

      if (data.hasManyResults) {
        count += `${data.nbHits} results`;
      } else if (data.hasOneResult) {
        count += `1 result`;
      } else {
        count += `no result`;
      }

      return html`<span>${count} found in ${data.processingTimeMS}ms</span>`;
    },
  },
});

HTML output

1
2
3
4
5
6
7
8
9
<div class="ais-Stats">
  <span class="ais-Stats-text">7,435 relevant results sorted out of 20,337 found in 1ms.</span>
</div>

<!-- or -->

<div class="ais-Stats">
  <span class="ais-Stats-text">20,337 results found in 1ms.</span>
</div>

Customize the UI with connectStats

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

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

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

Then it’s a 3-step process:

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

// 2. Create the custom widget
const customStats = connectStats(
  renderStats
);

// 3. Instantiate
search.addWidgets([
  customStats({
    // 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 renderStats = (renderOptions, isFirstRender) => {
  const {
    number hitsPerPage,
    number nbHits,
    boolean areHitsSorted,
    number nbSortedHits,
    number nbPages,
    number page,
    number processingTimeMS,
    string query,
    object widgetParams,
  } = renderOptions;

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

  // Render the widget
}

Rendering options

Parameter Description
hitsPerPage
type: number

The maximum number of hits returned per page.

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { hitsPerPage } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <p>${hitsPerPage} hits per page</p>
  `;
};
nbHits
type: number

The number of hits matched by the query.

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { nbHits } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <p>${nbHits} hits</p>
  `;
};
areHitsSorted
type: boolean

Indicates whether Relevant sort is applied to the result.

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { areHitsSorted } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <p>You're seeing ${areHitsSorted ? 'relevant' : 'all'} results.</p>
  `;
};
nbSortedHits
type: number

The number of sorted hits from Relevant sort.

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { nbSortedHits, nbHits } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <p>${nbSortedHits} relevant hit(s) sorted out of ${nbHits}</p>
  `;
};
nbPages
type: number

The number of returned pages. Calculation is based on the total number of hits (nbHits) divided by the number of hits per page (hitsPerPage), rounded up to the nearest integer.

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { nbPages } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <p>${nbPages} pages</p>
  `;
};
page
type: number

The position of the current page (zero-based).

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { page, nbPages } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <p>${page + 1}/${nbPages} pages</p>
  `;
};
processingTimeMS
type: number

The time the server took to process the request, in milliseconds. This doesn’t include network time.

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { processingTimeMS } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <p>Results found in ${processingTimeMS}ms</p>
  `;
};
query
type: string

The query sent to the server.

1
2
3
4
5
6
7
const renderStats = (renderOptions, isFirstRender) => {
  const { query } = renderOptions;

  document.querySelector('#stats').innerHTML = `
    <q>${query}</q>
  `;
};
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
const renderStats = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

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

// ...

search.addWidgets([
  customStats({
    container: document.querySelector('#stats'),
  })
]);

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 customStats = connectStats(
  renderStats
);

search.addWidgets([customStats()]);

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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Create the render function
const renderStats = (renderOptions, isFirstRender) => {
  const {
    nbHits,
    areHitsSorted,
    nbSortedHits,
    processingTimeMS,
    query,
    widgetParams,
  } = renderOptions;

  if (isFirstRender) {
    return;
  }

  let count = '';

  if (areHitsSorted) {
    if (nbSortedHits > 1) {
      count = `${nbSortedHits} relevant results`;
    } else if (nbSortedHits === 1) {
      count = '1 relevant result';
    } else {
      count = 'No relevant result';
    }
    count += ` sorted out of ${nbHits}`;
  } else {
    if (nbHits > 1) {
      count += `${nbHits} results`;
    } else if (nbHits === 1) {
      count += '1 result';
    } else {
      count += 'no result';
    }
  }

  widgetParams.container.innerHTML = `
    ${count} found in ${processingTimeMS}ms
    ${query ? `for <q>${query}</q>` : ''}
  `;
};

// Create the custom widget
const customStats = connectStats(renderStats);

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