The SortBy connector provides the logic to build a custom widget that will display a list of indices. With Algolia, this is most commonly used for changing ranking strategy. This allows a user to change how the hits are being sorted.
This connector provides the refine
function that allows to switch indices.
The connector provides to the rendering: refine()
to switch the current index and
options
that are the values that can be selected. refine
should be used
with options.value
.
const search= instantsearch(/* parameters */);
const makeSortBy= instantsearch.connectors.connectSortBy(
function renderFn(
renderOpts: SortByRenderingOptions,
isFirstRendering: boolean) {
// render the custom SortBy widget
}
);
const customSortBy = makeSortBy(instanceOpts: CustomSortByWidgetOptions);
search.addWidget(customSortBy);
string
The currently selected index.
Array<SortByItem>
All the available indices
(string) => undefined
Switches indices and triggers a new search.
boolean
true
if the last search contains no result.
Object
All original CustomSortByWidgetOptions
forwarded to the renderFn
.
Array<SortByItem>
Array of objects defining the different indices to choose from.
[(Array<object>) => Array<object>]
Function to transform the items passed to the templates.
// custom `renderFn` to render the custom SortBy widget
function renderFn(SortByRenderingOptions, isFirstRendering) {
if (isFirstRendering) {
SortByRenderingOptions.widgetParams.containerNode.html('<select></select>');
SortByRenderingOptions.widgetParams.containerNode
.find('select')
.on('change', function(event) {
SortByRenderingOptions.refine(event.target.value);
});
}
var optionsHTML = SortByRenderingOptions.options.map(function(option) {
return `
<option
value="${option.value}"
${SortByRenderingOptions.currentRefinement === option.value ? 'selected' : ''}
>
${option.label}
</option>
`;
});
SortByRenderingOptions.widgetParams.containerNode
.find('select')
.html(optionsHTML);
}
// connect `renderFn` to SortBy logic
var customSortBy = instantsearch.connectors.connectSortBy(renderFn);
// mount widget on the page
search.addWidget(
customSortBy({
containerNode: $('#custom-sort-by-container'),
items: [
{ value: 'instant_search', label: 'Most relevant' },
{ value: 'instant_search_price_asc', label: 'Lowest price' },
{ value: 'instant_search_price_desc', label: 'Highest price' },
],
})
);
Can't find what you are looking for? Open an issue, we'll get back to you.