Highlight and snippet your search results
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 functionsHighlight
and Snippet
.
Explore related content in the Algolia Academy
Extending widgets
Usage with templates
You have a direct access to the highlight and snippet functions through the template system.Style your widgets
All widgets in InstantSearch.js namespace are shipped with CSS class names that can be overridden. The format for those class names isais-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.
Loading the theme
No CSS is automatically loaded into your page but there are two themes that you can load manually:reset.css
satellite.css
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.
Using a CDN
The themes are available on jsDelivr:- Unminified:
- Minified:
HTML
Using npm and webpack
JavaScript
JavaScript
Other bundlers
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.CSS class override
You can override the class names of every widgets with thecssClasses
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:
JavaScript
Styling icons
You can style the icon colors using the widget class names:CSS
Translate your widgets
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.Example: translating the “Show more” label
Here is an example of a menu widget with a show more label translated in french:JavaScript
Templating your UI
InstantSearch.js widgets provide templates to customize parts of the UI. This lets you customize icons, provide a hit component, define an emptyuiState
, 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.
JavaScript
Using HTML strings with html
Every InstantSearch.js template provides anhtml
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.JavaScript
Internet Explorer 11 doesn’t support tagged template literals.
If you need to support Internet Explorer 11,
check out the suggested solutions.
Highlighting and snippeting
In bothhits
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.
Highlight
to highlight matching parts in Algolia results.Snippet
to snippet matching parts in Algolia results.ReverseHighlight
to highlight non-matching parts in Algolia results.ReverseSnippet
to highlight and snippet non-matching parts in Algolia results.
Loops and conditional rendering
You can use plain JavaScript to build dynamic templates. For example, you can useArray.map
to loop over an array and display a list.
JavaScript
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.JavaScript
Internet Explorer 11 support
You can’t usehtml
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 allhtml
expressions into regular function calls.
The recommended setup is to use @babel/preset-env
.
.babelrc
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 thehtml
function.
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.
Further optimizations
The providedhtml
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.JavaScript
.babelrc
If you’re destructuring objects,
make sure to also transpile it using
@babel/preset-env
.Using JSX
If you’re already using JSX in your project, you can directly return JSX templates.JSX
Using Hogan.js
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.JavaScript
Using classic HTML strings
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.JavaScript
Modify the list of items in widgets
Every widget and connector that handles a list of items exposes atransformItems
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.
Sorting
In this example, thetransformItems
option to order the items by label
in a ascending mode:
JavaScript
sortBy
option.
It accepts either an array of strings:
JavaScript
JavaScript
Filtering
This example uses thetransformItems
option to filter out items when the count is lower than 150.
JavaScript
Add manual values
By default, the values in aRefinementList
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”.
JavaScript
Display facets with no matches
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
Searching long lists
For some cases, you want to be able to directly search into a list of facet values. This can be achieved using thesearchable
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.
With widgets
Use thesearchable
prop to add a search box to supported widgets:
JavaScript
With connectors
You can implement your own search box for searching for items in lists when using supported connectors by using those provided parameters:searchForItems(query)
: call this function with a search query to trigger a new search for itemsisFromSearch
:true
when you are in search mode and the provideditems
are search items results
JavaScript
Apply default value to widgets
A question that comes up frequently is “How to instantiate arefinementList
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
How to provide search parameters
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 theconfigure
widget.
Here’s an example configuring the distinct
parameter:
JavaScript
Dynamic update of search parameters
To dynamically update the search parameters, you should create a new custom widget.Filter your results without widgets
Widgets already provide a lot of different ways to filter your results but sometimes you might have more complicated needs that require usage of thefilters
search parameter.
To avoid conflicts, don’t use filters on attributes already used with a widget.
JavaScript
Customize the complete UI of the widgets
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.Introduction to connectors
Anatomy of a connector
A connector is a function that will create a widget factory, which is a function that can create widget instances. They follow the pattern:JavaScript
JavaScript
Reuse connectors
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
When is the rendering function called?
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 argumentisFirstRendering
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
When is the unmount function called?
The unmount function is called when you remove a widget. Whensearch.removeWidgets([widget])
is called, InstantSearch.js cleans up the internal
data of the widget, and calls the unmount
function to clean up the DOM.
JavaScript
Customize widgets hands-on
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.A custom menu with jQuery
This example shows you how to create a new custom widget usingconnectMenu
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.
The first three steps focus on implementing the rendering function and then connecting it to InstantSearch.
Set up 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 theisFirstRendering
boolean as second argument of the render function.
Use this to insert the initial markup of your custom widget.
JavaScript
Display the available drop-down menu options
Then, on every render, you want to update and insert the available menu items as<option>
DOM nodes:
JavaScript
Make the drop-down menu interact with the search results
The menu connector comes with arefine()
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
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
Make connectors reusable
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
- a DOM container
- a title