Search is all about helping users understand the results. This is especially true when using text based search. When a user types a query in the search box, the results must show why the results are matching the query. That’s why Algolia implements a powerful highlighting that lets you display the matching parts of text attributes in the results. On top of that, Algolia implements snippeting to get only the meaningful part of a text, when attributes have a lot of content.This feature is already packaged for you in InstantSearch.js through two functions Highlight and Snippet.
All widgets in InstantSearch.js namespace are shipped with CSS class names that can be overridden.The format for those class names is ais-NameOfWidget-element--modifier (following the naming convention defined by SUIT CSS).The different class names used by each widget are described on their respective documentation pages. You can also inspect the underlying DOM and style accordingly.
No CSS is automatically loaded into your page but there are two themes that you can load manually:
reset.css
satellite.css
You should at least reset.css to avoid visual side effects caused by the new HTML semantics.The reset theme CSS is included within the satellite CSS, so there is no need to import it separately when you are using the satellite theme.
You can either copy paste the content into your own app or use a direct link to jsDelivr:
HTML
Report incorrect code
Copy
<!-- Include only the reset --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/reset-min.css" integrity="sha256-KvFgFCzgqSErAPu6y9gz/AhZAvzK48VJASu3DpNLCEQ=" crossorigin="anonymous"><!-- or include the full Satellite theme --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/satellite-min.css" integrity="sha256-woeV7a4SRDsjDc395qjBJ4+ZhDdFn8AqswN1rlTO64E=" crossorigin="anonymous">
// Include only the resetimport 'instantsearch.css/themes/reset.css';// or include the full Satellite themeimport 'instantsearch.css/themes/satellite.css';
Any other module bundler like Browserify or Parcel can be used to load the Algolia CSS. InstantSearch.js doesn’t rely on any specific module bundler or module loader.
You can override the class names of every widgets with the cssClasses option.
The different key provided by each widget to override the class are described on their respective documentation pages. Here is an example with the hits widget:
Most elements in InstantSearch.js widgets can be customized by means of templates.
Those templates can be text labels or complete piece of HTML.
Underneath, InstantSearch.js is using Hogan, which is an implementation of mustache, the logic-less templating.
InstantSearch.js widgets provide templates to customize parts of the UI.
This lets you customize icons, provide a hit component, define an empty uiState, and change the default labels.Templates can be either functions or strings. You can provide templates in several ways:
HTML strings with html (with function-based templates). This is the recommended way, especially if you’re using InstantSearch.js without a build step.
JSX templates (with function-based templates). This is useful if you’re already using a JSX implementation (like Preact) in your application.
Hogan.js templates (with string-based templates). This method is deprecated and shouldn’t be used for new templates.
“Classic” HTML strings (with string-based templates). This method is deprecated and shouldn’t be used for new templates.
You might want to customize a part of the widget that the template system doesn’t cover.
For these use cases take a look at the section extending widgets.
Every InstantSearch.js template provides an html function that you can use as a tagged template. Using html lets you safely provide templates as an HTML string.
It works directly in the browser, no need for a transpiler or a build step.
The html function is only available starting from v4.46.0.
In both hits and infiniteHits widgets, templates expose a set of built-in components to handle highlighting and snippeting. You can use either their function form, or interpolate them.
Passing a unique key attribute is helpful when mapping over items.
It helps the virtual DOM keep track of each element when they change, and update the UI efficiently.
You can’t use html as a tagged template in Internet Explorer 11.
Depending on your project setup,
you can work around this problem to still use html while providing compatible code to your Internet Explorer 11 users.
With Babel
If you’re already using Babel to compile your code for legacy browsers, you can transform all html expressions into regular function calls.The recommended setup is to use @babel/preset-env.
.babelrc
Report incorrect code
Copy
{ "presets": [["@babel/preset-env"]]}
With a shim
If you don’t have a build step in your project,
you can write a shim.
Tagged templates are regular functions with a specific signature,
so you can wrap their calls with a friendlier API to avoid using tagged template notation.This function takes templates either as static strings,
or as an array of interspersed chunks, splits them, and passes them to the html function.
Report incorrect code
Copy
function htmlShim(template, html) { if (typeof template === 'string') { return html([template]); } const parts = template.reduce( (acc, part, index) => { const isEven = index % 2 === 0; acc[Math.abs(Number(!isEven))].push(part); return acc; }, [[], []] ); return html(parts[0], ...parts[1]);}
The documented shim assumes every even array entry is a template string,
and every odd entry is a dynamic value. You can adapt it if you need a different behavior.
The provided html function works in the browser without any build step, with a negligible impact on memory and bundle size (< 600 bytes).For optimal performance, you can use the babel-plugin-htm Babel plugin to compile html into preact.createElement calls.
To use this plugin,
you need to adapt your code so that the pragma to replace html calls with is always accessible.
For example, instead of destructuring in the signature,
you need to name the parameter and destructure it in the function body—or not destructure it at all.
The parameter (here, params) must have the same name in every template.
You can provide templates using Hogan.js, a Mustache implementation. For a comprehensive reference, check the respective documentations.
Hogan.js and string-based templates are deprecated and won’t be supported in InstantSearch.js 5.
You can replace them with function-form templates and use either the provided html function
or JSX templates.
For more information, see Upgrade templates.
You can provide plain HTML strings using string-based templates.
They’re injected as HTML.
HTML strings and string-based templates are deprecated and won’t be supported in InstantSearch.js 5.
You can replace them with function-form templates and use either the provided html function
or JSX templates.
For more information, see Upgrade templates.
Every widget and connector that handles a list of items exposes a transformItems option.
This option is a function that takes the items as a parameter and expects to return the items back.
This option can be used to sort, filter, and add manual values.
search.addWidgets([ instantsearch.widgets.refinementList({ container: '#brands', attribute: 'brand', sortBy: (a, b) { // if a should be before b return -1 // if b should be before a return 1 // otherwise return 0 }, })]);
By default, the values in a RefinementList or a Menu are dynamic.
This means that the values are updated with the context of the search.
Most of the time this is the expected behavior,
but sometimes you may want to have a static list of values that never change.
To achieve this, you can use the connectors.This example uses the connectRefinementList
connector to display a static list of values.
This RefinementList will always display and only display the items “Apple” and “Microsoft”.
Hiding facets when they don’t match a query can be counter-intuitive.
However, because of the way Algolia handles faceting,
you have to rely on workarounds on the frontend to display facets when they have no hits.One way of displaying facets with no matches is by caching the results the first time you receive them.
Then, if the amount of real facet hits that Algolia returns is below the limit set,
you can append the cached facets to the list.This solution comes with limitations:
Facet hits coming from a facet search (“Search for facet values”) can’t work because Algolia doesn’t return facets that don’t match (the highlighting won’t work on cached items).
Sorting might need to be applied again in the transformItems function because the internal sorting happens before this function is called
JavaScript
Report incorrect code
Copy
function uniqBy(items, property) { const seen = {}; return items.filter(item => { const val = item[property]; if (seen[val]) { return false; } else { seen[val] = true; return true; } });}const searchClient = algoliasearch( 'latency', '6be0576ff61c053d5f9a3225e2a90f76');const indexName = 'instant_search';const brandAttribute = 'brand';const brandLimit = 10;const search = instantsearch({ indexName, searchClient,});const initialFacets = [];// On the first load, all facets returned by Algolia are stored// so we can append them to the returned facets when Algolia return enough.// We set their `count` to 0 because they'll show up when nothing// else matches.// Note that this triggers another query.searchClient .searchForFacetValues([ { indexName, params: { facetName: brandAttribute, facetQuery: '', maxFacetHits: brandLimit, }, }, ]) .then(([{ facetHits }]) => { initialFacets.push( ...facetHits.map(facet => ({ ...facet, label: facet.value, value: facet.value, isRefined: false, count: 0, })) ); });search.addWidgets([ instantsearch.widgets.refinementList({ container: '#brand-list', attribute: brandAttribute, limit: brandLimit, transformItems: items => { // If Algolia doesn't return enough results, we lose track of a // potentially refined facet. // For example, if you refine on "Apple", then search for "chromecast", // "Apple" is no longer returned, and we don't know that it was selected // based on the initial facets. // We need to keep track of the last state to reflect the fact that it // was refined in the UI. initialFacets.forEach((facet, index) => { const updatedItem = items.find(item => item.value === facet.value); if (updatedItem) { initialFacets[index] = { ...updatedItem, count: 0, }; } }); // If a cached facet is already returned by Algolia, we want it to be // displayed rather than to display its cached value. // You might need to sort the items again here because the internal // sorting happens before `transformItems` is called. return uniqBy([...items, ...initialFacets], 'value').slice(0, brandLimit); }, })]);search.start();
For some cases, you want to be able to directly search into a list of facet values.
This can be achieved using the searchable prop on widgets like refinementList or connectRefinementList connector. To enable this feature, you’ll need to make the attribute searchable using the API or the dashboard.
A question that comes up frequently is “How to instantiate a refinementList widget with a pre-selected item?”. For this use case, you can use the configure widget.The following example instantiates a search page with a default query of “apple” and will show a category menu where the item “Cell Phones” is already selected:
JavaScript
Report incorrect code
Copy
const search = instantsearch({ indexName: 'instant_search', searchClient,});search.addWidgets([ instantsearch.widgets.refinementList({ container: '#category', attribute: 'categories', }), // This needs to be after the refinement list has been declared instantsearch.widgets.configure({ query: 'apple', disjunctiveFacetsRefinements: { categories: ['Cell Phones'], }, }), instantsearch.widgets.hits({ container: '#hits', })]);
Algolia has a wide range of parameters.
If one of the parameters you want to use isn’t covered by any widget or connector,
then you can use the configure widget.Here’s an example configuring the distinct parameter:
Widgets already provide a lot of different ways to filter your results but sometimes you might have more complicated needs that require usage of the filters search parameter.
To avoid conflicts, don’t use filters on attributes already used with a widget.
InstantSearch.js comes with widgets that have a standardized rendering. If you feel limited by the options provided, you can go further using connectors.Connectors are the render-less counterparts of the widgets. They encapsulate
all the logic needed for making search widgets. Each one of them is specialized
to make a certain type of widget.If you want to create a type of widget that isn’t available, you should then
create a custom widget.
Connectors are meant to be reusable, it’s important to be able to pass options to
the rendering of each single widget instance when instantiating them. That’s why
all the options passed to the newly created widget factory will be forwarded to the
rendering.In the following example you want to configure the DOM element that will
host the widget:
JavaScript
Report incorrect code
Copy
const makeHits = instantsearch.connectors.connectHits( function renderHits({ items, widgetParams }, isFirstRendering) { // widgetParams contains all the option used to call the widget factory const container = widgetParams.container; $(container).html(items.map(item => JSON.stringify(item))); });const search = instantsearch(/* options */);search.addWidgets([ makeHits({container: $('#hits-1')}), makeHits({container: $('#hits-2')})]);
The rendering function is called before the first search (init lifecycle step)
and each time results come back from Algolia (render lifecycle step).Depending on the method you are relying on to render your widget, you might
want to use the first call to create the basic DOM structure (like when using
vanilla JS or jQuery).To be able to identify at which point of the lifecycle the rendering function is
called, a second argument isFirstRendering is provided to the rendering function.This parameter is there to be able to only do some operations once, like creating
the basic structure of the new widget once. The latter calls can then be used to
only update the DOM.
JavaScript
Report incorrect code
Copy
const makeHits = instantsearch.connectors.connectHits( function renderHits({ hits }, isFirstRendering) { if (isFirstRendering) { // Do some initial rendering } // Do the normal rendering });const search = instantsearch(/* options */);search.addWidgets([makeHits()]);
The unmount function is called when you remove a widget.When search.removeWidgets([widget]) is called, InstantSearch.js cleans up the internal
data of the widget, and calls the unmount function to clean up the DOM.
InstantSearch.js comes bundled with a set of 15+ UI components. Each of them
has options to manipulate CSS classes or even modifying part of the HTML
output (templates).To go a step further in terms of customization, InstantSearch.js offers connectors
that contain the logic of the widgets without their rendering.
This example shows you how to create a new custom widget using connectMenu connector. It covers,
step by step, how to write a render function used by the connector.For simplicity, custom widgets use jQuery to manipulate the DOM.
Since these examples use jQuery,
you only want to update the changing parts of the markup at every render.To help you to do that, the connectors API provides the isFirstRendering boolean as second argument of the render function.
Use this to insert the initial markup of your custom widget.
JavaScript
Report incorrect code
Copy
const customMenuRenderFn = (renderParams, isFirstRendering) => { if (isFirstRendering) { // insert needed markup in the DOM // here we want a `<select></select>` element and the title $(document.body).append(` <h1>My first custom menu widget</h1> <select></select> `); }}
If you use a rendering library such as React, you can omit this part because React will compute this for you.
Then, on every render, you want to update and insert the available menu items as <option> DOM nodes:
JavaScript
Report incorrect code
Copy
const customMenuRenderFn = (renderParams, isFirstRendering) => { if (isFirstRendering) { $(document.body).append(` <h1>My first custom menu widget</h1> <select></select> `); } // `renderParams` is an object containing all the information // you need to create a custom widget. const items = renderParams.items; // Transform `items[]` to HTML markup: // Each item comes with a `value` and `label`, it will also have a boolean to true // called `isRefined` when the current menu item is selected by users. const optionsHTML = items.map(({value, isRefined, label, count}) => ` <option value="${value}" ${isRefined ? ' selected' : ''}> ${label} (${count}) </option>` ); // Then replace the content of `<select></select>` node with the new menu items markup. $(document.body).find('select').html(optionsHTML);}
Now all the menu options are displayed on the page but nothing is updated when the user selects a new option. To fix that, connect the drop-down menu to the search.
Make the drop-down menu interact with the search results
The menu connector comes with a refine() function in the first argument renderParams object.
You need to call this refine() function every time a user select another option to refine the search results:
JavaScript
Report incorrect code
Copy
const customMenuRenderFn = (renderParams, isFirstRendering) => { if (isFirstRendering) { $(document.body).append(` <h1>My first custom menu widget</h1> <select></select> `); // We will bind the `<select>` change event on first render // because we don't want to create new listeners on every render // for potential performance issues: const refine = renderParams.refine; // we will use `event.target.value` to identify // which option is selected and then refine it: $(document.body).find('select').on('change', ({target}) => { refine(target.value); }); } const items = renderParams.items; const optionsHTML = items.map(({value, isRefined, label, count}) => ` <option value="${value}" ${isRefined ? 'selected' : ''}> ${label} (${count}) </option> `); $(document.body).find('select').html(optionsHTML);}
Now every time a user selects a new option in the drop-down menu,
it triggers a new search to refine the search results.
Mount the custom drop-down menu widget on your page
You’ve just written the render function and can now use it with the menu connector.
This will create a new widget factory for the custom drop-down menu widget.Use this factory in your search:
JavaScript
Report incorrect code
Copy
const customMenuRenderFn = (renderParams, isFirstRendering) => { if (isFirstRendering) { $(document.body).append(` <h1>My first custom menu widget</h1> <select></select> `); const refine = renderParams.refine; $(document.body).find('select').on('change', ({target}) => { refine(target.value); }); } const items = renderParams.items; const optionsHTML = items.map(({value, isRefined, label, count}) => ` <option value="${value}" ${isRefined ? 'selected' : ''}> ${label} (${count}) </option> `); $(document.body).find('select').html(optionsHTML);}// Create a new factory of the custom menu select widget:const dropdownMenu = instantsearch.connectors.connectMenu(customMenuRenderFn);// Instantiate custom widget and display it on the page.// Custom widgets that are created with connectors accepts// the same options as a built-in widget, for instance// the menu widget takes a mandatory `attribute` option// so we have to do the same:search.addWidgets([ dropdownMenu({ attribute: 'categories' })]);
This example works on a single DOM element, which means that you won’t be able to re-use it for another attribute.
Connectors are meant to be reusable, it’s important to be able to pass options to
the rendering of each single widget instance when instantiating them.That’s why all the options passed to the newly created widget factory will be forwarded to the
rendering.Now update your custom render function to configure the DOM element where the widget is mounted and also the title:
JavaScript
Report incorrect code
Copy
const customMenuRenderFn = (renderParams, isFirstRendering) => { // widgetParams contains all the original options used to instantiate the widget on the page. const container = renderParams.widgetParams.containerNode; const title = renderParams.widgetParams.title || 'My first custom menu widget'; if (isFirstRendering) { // Replace `document.body` with the container provided by users // and also the new title $(container).append(` <h1>${title}</h1> <select></select> `); const refine = renderParams.refine; $(container).find('select').on('change', ({target}) => { refine(target.value); }); } const items = renderParams.items; const optionsHTML = items.map(({value, isRefined, label, count}) => ` <option value="${value}" ${isRefined ? 'selected' : ''}> ${label} (${count}) </option> `); $(container).find('select').html(optionsHTML);}const dropdownMenu = instantsearch.connectors.connectMenu(customMenuRenderFn);// Now you can use the dropdownMenu at two different places in the DOM:// (since they use the same `attribute` they will display the same options)search.addWidgets([ dropdownMenu({ attribute: 'categories', containerNode: '#first-dropdown', }), dropdownMenu({ attribute: 'categories', containerNode: '#second-dropdown', })]);
These steps introduced a way to provide custom parameters: