Skip to main content
Signature
sortBy({
  container: string | HTMLElement,
  items: object[],
  // Optional parameters
  cssClasses?: object,
  transformItems?: function,
});
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 users 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

JavaScript
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
string | HTMLElement
required
The CSS Selector or HTMLElement to insert the widget into.
sortBy({
  // ...
  container: "#sort-by",
});
items
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.
JavaScript
sortBy({
  // ...
  items: [
    { label: "Featured", value: "instant_search" },
    { label: "Price (asc)", value: "instant_search_price_asc" },
    { label: "Price (desc)", value: "instant_search_price_desc" },
  ],
});
cssClasses
object
default:"{}"
The CSS classes you can override:
  • root. The root element of the widget.
  • select. Theselect element.
  • option. The option elements of the select.
JavaScript
sortBy({
  // ...
  cssClasses: {
    root: "MyCustomSortBy",
    select: ["MyCustomSortBySelect", "MyCustomSortBySelect--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
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

HTML
<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.
import { connectSortBy } from "instantsearch.js/es/connectors";
Then it’s a 3-step process:
JavaScript
// 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).
JavaScript
const renderSortBy = (renderOptions, isFirstRender) => {
  const { options, currentRefinement, canRefine, refine, widgetParams } =
    renderOptions;

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

  // Render the widget
};

Rendering options

options
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.
JavaScript
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
string
The currently selected index.
JavaScript
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
boolean
since: v4.45.0
Whether the search can be refined.
JavaScript
const renderSortBy = (renderOptions, isFirstRender) => {
  // `canRefine` is only available from v4.45.0
  // Use `hasNoResults` in earlier minor versions.
  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
function
Switches indices and triggers a new search.
JavaScript
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
object
All original widget options forwarded to the render function.
JavaScript
const renderSortBy = (renderOptions, isFirstRender) => {
  const { widgetParams } = renderOptions;

  widgetParams.container.innerHTML = "...";
};

// ...

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

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

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

Instance options

items
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.
JavaScript
customSortBy({
  items: [
    { label: "Featured", value: "instant_search" },
    { label: "Price (asc)", value: "instant_search_price_asc" },
    { label: "Price (desc)", value: "instant_search_price_desc" },
  ],
});
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
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

<div id="sort-by"></div>
I