API Reference / React InstantSearch Hooks / <SortBy>
Signature
<SortBy
  items={SortByProps['items']}
  // Optional parameters
  transformItems={SortByProps['transformItems']}
  classNames={Partial<SortByClassNames>}
  ...props={React.ComponentProps<'div'>}
/>

About this widget

<SortBy> is a widget to sort by specified indices.

This lets you display a list of indices for the user to select, allowing them to change how hits are sorted using replica indices.

You must set all indices you define in items as replicas of the main index.

You can also create your own UI with useSortBy().

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SortBy } from 'react-instantsearch-hooks-web';

const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <SortBy
        items={[
          { label: 'Featured', value: 'instant_search' },
          { label: 'Price (asc)', value: 'instant_search_price_asc' },
          { label: 'Price (desc)', value: 'instant_search_price_desc' },
        ]}
      />
    </InstantSearch>
  );
}

Props

items
type: SortByProps['items']
Required

A list of different indices to choose from.

1
2
3
4
5
6
7
<SortBy
  items={[
    { label: 'Featured', value: 'instant_search' },
    { label: 'Price (asc)', value: 'instant_search_price_asc' },
    { label: 'Price (desc)', value: 'instant_search_price_desc' },
  ]}
/>
transformItems
type: SortByProps['transformItems']

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
<SortBy
  // ...
  transformItems={(items) => {
    return items.map(item => ({
      ...item,
      label: item.label.toUpperCase(),
    }));
  }}

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

CSS classes to pass to the widget’s elements. This is useful to style widgets with class-based CSS frameworks like Bootstrap or Tailwind CSS.

  • root: The root element of the widget.
  • select: The select element.
  • option: The option element.
1
2
3
4
5
6
7
<SortBy
  // ...
  classNames={{
    root: 'MyCustomSortBy',
    select: 'MyCustomSortBySelect MyCustomSortBySelect--subclass',
  }}
/>
...props
type: React.ComponentProps<'div'>
Optional

Any <div> prop to forward to the root element of the widget.

1
2
3
4
5
<SortBy
  // ...
  className="MyCustomSortBy"
  title="My custom title"
/>

Hook

React InstantSearch Hooks let you create your own UI for the <SortBy> widget with useSortBy(). Hooks provide APIs to access the widget state and interact with InstantSearch.

The useSortBy() Hook accepts parameters and returns APIs.

Usage

First, create your React component:

import { useSortBy } from 'react-instantsearch-hooks-web';

function CustomSortBy(props) {
  const {
    initialIndex,
    currentRefinement,
    options,
    refine,
    hasNoResults,
  } = useSortBy(props);

  return <>{/* Your JSX */}</>;
}

Then, render the widget:

<CustomSortBy {...props} />

Parameters

Hooks accept parameters. You can pass them manually, or forward the props from your custom component.

When you provide a function to Hooks, make sure to pass a stable reference with useCallback() to avoid rendering endlessly. Objects and arrays are memoized so you don’t have to stabilize them.

items
type: UseSortByProps['items']
Required

A list of different indices to choose from.

1
2
3
4
5
6
7
const sortByApi = useSortBy({
  items: [
    { label: 'Featured', value: 'instant_search' },
    { label: 'Price (asc)', value: 'instant_search_price_asc' },
    { label: 'Price (desc)', value: 'instant_search_price_desc' },
  ],
});
transformItems
type: UseSortByProps['transformItems']

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
const sortByApi = useSortBy({
  // ...
  transformItems(items) {
    return items.map(item => ({
      ...item,
      label: item.label.toUpperCase(),
    }));
  },

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

APIs

Hooks return APIs, such as state and functions. You can use them to build your UI and interact with React InstantSearch.

initialIndex
type: string

The initially selected index.

currentRefinement
type: string

The currently selected index.

options
type: SortByItem[]

All the available indices.

1
2
3
4
5
6
7
8
9
10
type SortByItem = {
  /**
   * The name of the index to target.
   */
  value: string;
  /**
   * The label of the index to display.
   */
  label: string;
};
refine
type: (value: string) => void

Switches indices and triggers a new search.

hasNoResults
type: boolean

Whether the last search contains no results.

Example

1
2
3
4
5
6
7
8
import React from 'react';
import { useSortBy } from 'react-instantsearch-hooks-web';

function SortBy(props) {
  const { currentRefinement, options, refine } = useSortBy(props);

  return <>{/* Your JSX */}</>;
}
Did you find this page helpful?