Skip to main content
The SortBy connector provides the logic to build a custom widget that displays a list of indices or sorting strategies. This is commonly used for changing ranking strategy. This connector supports two sorting modes:
  1. Index-based (traditional): Uses the value property to switch between different indices
  2. Strategy-based (composition mode): Uses the strategy property to apply sorting strategies via the sortBy search parameter (only available when using Algolia Compositions)

Usage

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

const customSortBy = connectSortBy(
  (renderOptions, isFirstRender) => {
    const { options, currentRefinement, refine, widgetParams } = renderOptions;
    const { container } = widgetParams;
    
    container.innerHTML = `
      <select>
        ${options.map(option => `
          <option 
            value="${option.value}"
            ${option.value === currentRefinement ? 'selected' : ''}
          >
            ${option.label}
          </option>
        `).join('')}
      </select>
    `;
    
    container.querySelector('select').addEventListener('change', (e) => {
      refine(e.target.value);
    });
  }
);

search.addWidgets([
  customSortBy({
    container: document.querySelector('#sort-by'),
    items: [
      { label: 'Relevance', value: 'instant_search' },
      { label: 'Price (asc)', value: 'instant_search_price_asc' },
      { label: 'Price (desc)', value: 'instant_search_price_desc' },
    ],
  }),
]);

Usage with Sorting Strategies (Composition Mode)

search.addWidgets([
  customSortBy({
    container: document.querySelector('#sort-by'),
    items: [
      { label: 'Relevance', strategy: 'relevance' },
      { label: 'Price (asc)', strategy: 'price_asc' },
      { label: 'Price (desc)', strategy: 'price_desc' },
    ],
  }),
]);

Connector Options

items
Array<SortByItem>
required
Array of objects defining the different indices or strategies to choose from.Each item must have either:
  • value: The name of the index to target (for index-based sorting)
  • strategy: The name of the sorting strategy (for composition mode)
And also:
  • label: The label of the index or strategy to display
transformItems
(items: object[]) => object[]
Function to transform the items passed to the templates.

Render Options

options
Array<{ value: string, label: string }>
All the available indices and strategies.
currentRefinement
string
The currently selected index or strategy.
initialIndex
string
The initially selected index or strategy.
refine
(value: string) => void
Switches indices or strategies and triggers a new search.
canRefine
boolean
true if we can refine.
hasNoResults
boolean
true if the last search contains no results.
This parameter is deprecated. Use canRefine instead.
widgetParams
object
The options passed to the connector.