API Reference / InstantSearch.js / sortBy
Signature
sortBy({
  container: string|HTMLElement,
  items: object[],
  // Optional parameters
  cssClasses: object,
  transformItems: function,
});
Import
1
import { sortBy } from 'instantsearch.js/es/widgets';

About this widget

The sortBy widget displays a list of indices, allowing a user to change the way hits are sorted (with replica indices). Another common use case is to let the user switch between different indices.

For this widget to work, you must define all indices that you pass down as options as replicas of the main index.

Examples

1
2
3
4
5
6
7
8
sortBy({
  container: '#sort-by',
  items: [
    { label: 'Featured', value: 'instant_search' },
    { label: 'Price (asc)', value: 'instant_search_price_asc' },
    { label: 'Price (desc)', value: 'instant_search_price_desc' },
  ],
});

Options

container
type: string|HTMLElement
Required

The CSS Selector or HTMLElement to insert the widget into.

1
2
3
4
sortBy({
  // ...
  container: '#sort-by',
});
items
type: object[]
Required

The list of indices to search in, with each item:

  • label: string: the label of the index to display.
  • value: string: the name of the index to target.
1
2
3
4
5
6
7
8
sortBy({
  // ...
  items: [
    { label: 'Featured', value: 'instant_search' },
    { label: 'Price (asc)', value: 'instant_search_price_asc' },
    { label: 'Price (desc)', value: 'instant_search_price_desc' },
  ],
});
cssClasses
type: object
default: {}
Optional

The CSS classes to override.

  • root: the root element of the widget.
  • select: theselect element.
  • option: the option elements of the select.
1
2
3
4
5
6
7
8
9
10
sortBy({
  // ...
  cssClasses: {
    root: 'MyCustomSortBy',
    select: [
      'MyCustomSortBySelect',
      'MyCustomSortBySelect--subclass',
    ],
  },
});
transformItems
type: function
default: items => items
Optional

Receives the items and is called before displaying them. Should return a new array with the same shape as the original array. Useful for transforming, removing, or reordering items.

In addition, the full results data is available, which includes all regular response parameters, as well as parameters from the helper (for example disjunctiveFacetsRefinements).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sortBy({
  // ...
  transformItems(items) {
    return items.map(item => ({
      ...item,
      label: item.label.toUpperCase(),
    }));
  },
});

/* or, combined with results */
sortBy({
  // ...
  transformItems(items, { results }) {
    return results?.nbPages < 4
      ? items.filter(item => item.value === 'instant_search')
      : items;
  },
});

HTML output

1
2
3
4
5
6
7
<div class="ais-SortBy">
  <select class="ais-SortBy-select">
    <option class="ais-SortBy-option" value="instant_search">Featured</option>
    <option class="ais-SortBy-option" value="instant_search_price_asc">Price asc.</option>
    <option class="ais-SortBy-option" value="instant_search_price_desc">Price desc.</option>
  </select>
</div>

Customize the UI with connectSortBy

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

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

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

Then it’s a 3-step process:

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

// 2. Create the custom widget
const customSortBy = connectSortBy(
  renderSortBy
);

// 3. Instantiate
search.addWidgets([
  customSortBy({
    // 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 renderSortBy = (renderOptions, isFirstRender) => {
  const {
    object[] options,
    string currentRefinement,
    boolean canRefine,
    function refine,
    object widgetParams,
  } = renderOptions;

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

  // Render the widget
}

Rendering options

options
type: object[]

The list of items the widget can display, with each item:

  • label: string: the label of the index to display.
  • value: string: the name of the index to target.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const renderSortBy = (renderOptions, isFirstRender) => {
  const { options } = renderOptions;

  document.querySelector('#sort-by').innerHTML = `
    <select>
      ${options
        .map(
          option => `
            <option value="${option.value}">
              ${option.label}
            </option>
          `
        )
        .join('')}
    </select>
  `;
};
currentRefinement
type: string

The currently selected index.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const renderSortBy = (renderOptions, isFirstRender) => {
  const { options, currentRefinement } = renderOptions;

  document.querySelector('#sort-by').innerHTML = `
    <select>
      ${options
        .map(
          option => `
            <option
              value="${option.value}"
              ${option.value === currentRefinement ? 'selected' : ''}
            >
              ${option.label}
            </option>
          `
        )
        .join('')}
    </select>
  `;
};
canRefine
type: boolean

Whether the search can be refined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const renderSortBy = (renderOptions, isFirstRender) => {
  const { options, currentRefinement, canRefine } = renderOptions;

  document.querySelector('#sort-by').innerHTML = `
    <select ${!canRefine ? 'disabled' : ''}>
      ${options
        .map(
          option => `
            <option
              value="${option.value}"
              ${option.value === currentRefinement ? 'selected' : ''}
            >
              ${option.label}
            </option>
          `
        )
        .join('')}
    </select>
  `;
};
refine
type: function

Switches indices and triggers a new search.

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
const renderSortBy = (renderOptions, isFirstRender) => {
  const { options, currentRefinement, refine } = renderOptions;

  const container = document.querySelector('#sort-by');

  if (isFirstRender) {
    const select = document.createElement('select');

    select.addEventListener('change', event => {
      refine(event.target.value);
    });

    container.appendChild(select);
  }

  container.querySelector('select').innerHTML = `
    ${options
      .map(
        option => `
          <option
            value="${option.value}"
            ${option.value === currentRefinement ? 'selected' : ''}
          >
            ${option.label}
          </option>
        `
      )
      .join('')}
  `;
};
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 renderSortBy = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

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

// ...

search.addWidgets([
  customSortBy({
    container: document.querySelector('#sort-by'),
  })
]);

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 customSortBy = connectSortBy(
  renderSortBy
);

search.addWidgets([
  customSortBy({
    items: object[],
    // Optional parameters
    transformItems: function,
  })
]);

Instance options

items
type: object[]
Required

The list of indices to search in, with each item:

  • label: string: the label of the index to display.
  • value: string: the name of the index to target.
1
2
3
4
5
6
7
customSortBy({
  items: [
    { label: 'Featured', value: 'instant_search' },
    { label: 'Price (asc)', value: 'instant_search_price_asc' },
    { label: 'Price (desc)', value: 'instant_search_price_desc' },
  ],
});
transformItems
type: function
default: items => items
Optional

Receives the items and is called before displaying them. Should return a new array with the same shape as the original array. Useful for transforming, removing, or reordering items.

In addition, the full results data is available, which includes all regular response parameters, as well as parameters from the helper (for example disjunctiveFacetsRefinements).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
customSortBy({
  transformItems(items) {
    return items.map(item => ({
      ...item,
      label: item.label.toUpperCase(),
    }));
  },
});

/* or, combined with results */
customSortBy({
  // ...
  transformItems(items, { results }) {
    return results?.nbPages < 4
      ? items.filter(item => item.value === 'instant_search')
      : items;
  },
});

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
52
53
54
// Create the render function
const renderSortBy = (renderOptions, isFirstRender) => {
  const {
    options,
    currentRefinement,
    canRefine,
    refine,
    widgetParams,
  } = renderOptions;

  if (isFirstRender) {
    const select = document.createElement('select');

    select.addEventListener('change', event => {
      refine(event.target.value);
    });

    widgetParams.container.appendChild(select);
  }

  const select = widgetParams.container.querySelector('select');

  select.disabled = !canRefine;

  select.innerHTML = `
    ${options
      .map(
        option => `
          <option
            value="${option.value}"
            ${option.value === currentRefinement ? 'selected' : ''}
          >
            ${option.label}
          </option>
        `
      )
      .join('')}
  `;
};

// Create the custom widget
const customSortBy = connectSortBy(renderSortBy);

// Instantiate the custom widget
search.addWidgets([
  customSortBy({
    container: document.querySelector('#sort-by'),
    items: [
      { label: 'Featured', value: 'instant_search' },
      { label: 'Price (asc)', value: 'instant_search_price_asc' },
      { label: 'Price (desc)', value: 'instant_search_price_desc' },
    ],
  })
]);
Did you find this page helpful?