Search code examples
searchautocompletehighlightalgolia

Algolia autocomplete: How do I highlight items?


I use Algolia autocomplete in "standalone" mode, meaning without the commercial Algolia service to return the search results; I have my own server respond with an array of search results.

How do I highlight matches in my returned items/strings (search results)?


Solution

  • The backend must return results that are already highlighted using a tag such as: <mark>this-is-to-be-highlighted</mark>. Here's an example result array for an search for "pie":

    const items = [
      { some_attribute: 'Apple <mark>pie</mark>' },
      { some_attribute: 'American <mark>pie</mark>' },
      { some_attribute: 'Chocolate <mark>pie</mark>' }
    ]
    

    The complete javascript code would then be something like this:

    import { autocomplete } from "@algolia/autocomplete-js"
    
    
    autocomplete({
      container: '#search_input',
    
      // ...
    
      getSources({ query }) {
    
        // This would be an example response from your server
        const items = [
          { some_attribute: 'Apple <mark>pie</mark>' },
          { some_attribute: 'American <mark>pie</mark>' },
          { some_attribute: 'Chocolate <mark>pie</mark>' }
        ]
    
        return [
    
          {
            sourceId: 'pies',
    
            getItems({ query }) {
              const HIGHLIGHT_PRE_TAG = '__aa-highlight__'
              const HIGHLIGHT_POST_TAG = '__/aa-highlight__'
    
              return items.map((item) => ({
                item,
                _highlightResult: {
                  some_attribute: {
                    value: item.some_attribute
                      .replace(/<mark>/g, HIGHLIGHT_PRE_TAG)
                      .replace(/<\/mark>/g, HIGHLIGHT_POST_TAG)
                  }
                }
              }))
            },
    
            templates: {
    
              // ...
    
              item({ item, components, html }) {
                return html`<div className="aa-ItemWrapper">
                  <div className="aa-ItemContent">
                    <div className="aa-ItemContentBody">
                      <div className="aa-ItemContentTitle">
                        ${components.Highlight({ hit: item, attribute: 'some_attribute' })}
                      </div>
                    </div>
                  </div>
                </div>`
              },
    
              // ...
    
            }
          },
    
          // ...
    
        ]
    
      },
    
      // ...
    
    })