The <SortBy> component displays a dropdown to change the sort order of search results by selecting different indices.
Import
import { SortBy } from 'react-instantsearch';
Props
items
Array<{ label: string; value: string }>
required
The indices to display in the dropdown.<SortBy
items={[
{ label: 'Most relevant', value: 'products' },
{ label: 'Price (low to high)', value: 'products_price_asc' },
{ label: 'Price (high to low)', value: 'products_price_desc' },
]}
/>
Transform the items before displaying them.<SortBy
items={[
{ label: 'Relevant', value: 'products' },
{ label: 'Price ASC', value: 'products_price_asc' },
]}
transformItems={(items) =>
items.map((item) => ({
...item,
label: item.label.toUpperCase(),
}))
}
/>
CSS classes to customize the component styling.
Example
import { InstantSearch, SortBy, Hits } from 'react-instantsearch';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
const searchClient = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey'
);
function App() {
return (
<InstantSearch searchClient={searchClient} indexName="products">
<SortBy
items={[
{ label: 'Most relevant', value: 'products' },
{ label: 'Price (low to high)', value: 'products_price_asc' },
{ label: 'Price (high to low)', value: 'products_price_desc' },
{ label: 'Newest first', value: 'products_date_desc' },
]}
/>
<Hits />
</InstantSearch>
);
}
Make sure to create replica indices in your Algolia dashboard with the appropriate sorting configuration before using this component.
Creating Replica Indices
To use different sort orders, you need to create replica indices:
- Go to your Algolia dashboard
- Navigate to your index
- Go to “Replicas” tab
- Create replicas with different sorting:
products_price_asc: Sort by price ascending
products_price_desc: Sort by price descending
products_date_desc: Sort by date descending