UI libraries / InstantSearch.js / Widgets
Signature
components.Snippet({
  attribute: string,
  hit: object,
  // Optional parameters
  highlightedTagName: string,
  nonHighlightedTagName: string,
  separator: string,
  cssClasses: object,
});

About this widget

The snippet function returns attributes in your search results in a shorter form (a snippet). Snippeted attributes are also highlighted.

This function uses Algolia’s snippeting feature in combination with the hits or infiniteHits widgets.

To determine which attributes should be snippeted, first set them from the Algolia dashboard, the CLI, or with the API (using the attributesToSnippet parameter):

1
2
3
4
5
search.addWidgets([
  configure({
    attributesToSnippet: ['description'],
  })
]);

With attributesToSnippet, you can also set the snippet’s size to a specific number of words (it defaults to 10). For example, attributesToSnippet: ['description:5'].

Examples

1
2
3
4
5
6
7
8
9
10
11
hits({
  container: '#hits',
  templates: {
    item(hit, { html, components }) {
      return html`
        <h2>${hit.name}</h2>
        <p>${components.Snippet({ attribute: 'description', hit })}</p>
      `;
    },
  },
});

Options

attribute
type: string
Required

The attribute of the record to snippet. For deeply nested objects, specify a dot-separated value like actor.bio.

1
2
3
4
components.Snippet({
  // ...
  attribute: 'description.full',
});
hit
type: object
Required

Original hit object provided to the function. The value is already bound to the function inside a string template, so you don’t have to provide it. For this to work, the provided object must have a _snippetResult[attribute].value property.

1
2
3
4
components.Snippet({
  // ...
  hit: item,
});
highlightedTagName
type: string
default: mark
Optional

The name of the HTML element to wrap the snippeted parts of the string.

1
2
3
4
components.Snippet({
  // ...
  highlightedTagName: 'em',
});
nonHighlightedTagName
type: string
default: "span"
Optional

The HTML element that wraps the non-highlighted parts of the string.

1
2
3
4
components.Snippet({
  // ...
  nonHighlightedTagName: 'div',
});
separator
type: string
default: ", "
Optional

The character between each item when the attribute to highlight is an array.

1
2
3
4
components.Snippet({
  // ...
  separator: ' - ',
});
cssClasses
type: object
default: {}
Optional

The CSS classes you can override:

  • root: the component’s root element.
  • highlighted: the highlighted parts.
  • nonHighlighted: the non-highlighted parts.
  • separator: the separator elements between highlighted parts.
1
2
3
4
5
6
7
8
9
10
components.Snippet({
  // ...
  cssClasses: {
    root: 'MyCustomSnippet',
    highlighted: [
      'MyCustomSnippetPart',
      'MyCustomSnippetPart--subclass',
    ],
  },
});

HTML output

1
<span>This is the <mark class="ais-Snippet-highlighted">highlighted text</mark></span>
Did you find this page helpful?