The <Snippet> component displays snippeted (truncated) parts of a search result attribute with highlighted matches.
Import
import { Snippet } from 'react-instantsearch';
Props
The search result object containing snippet information.<Snippet hit={hit} attribute="description" />
attribute
string | string[]
required
The attribute to snippet. Can be a string or array for nested attributes.// Simple attribute
<Snippet hit={hit} attribute="description" />
// Nested attribute
<Snippet hit={hit} attribute={['content', 'body']} />
The HTML tag to use for highlighted parts.<Snippet hit={hit} attribute="description" highlightedTagName="em" />
The HTML tag to use for non-highlighted parts.<Snippet
hit={hit}
attribute="description"
nonHighlightedTagName="span"
/>
The separator to use when the attribute is an array.<Snippet hit={hit} attribute="tags" separator=" | " />
CSS classes to customize the component styling.
Example
import { InstantSearch, SearchBox, Hits, Highlight, Snippet } from 'react-instantsearch';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
const searchClient = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey'
);
function Hit({ hit }) {
return (
<article>
<h1>
<Highlight hit={hit} attribute="title" />
</h1>
<p>
<Snippet hit={hit} attribute="description" />
</p>
</article>
);
}
function App() {
return (
<InstantSearch searchClient={searchClient} indexName="articles">
<SearchBox />
<Hits hitComponent={Hit} />
</InstantSearch>
);
}
Difference from Highlight
The <Snippet> component displays a truncated version of the attribute content centered around the matching terms, while <Highlight> displays the full content.
// Highlight: Shows full content
<Highlight hit={hit} attribute="description" />
// Output: "This is a long description with the search term somewhere in the middle of a very long text"
// Snippet: Shows truncated content around matches
<Snippet hit={hit} attribute="description" />
// Output: "...with the search term somewhere..."
Make sure to enable snippeting in your index settings or using the attributesToSnippet search parameter.
With Custom Styling
function Hit({ hit }) {
return (
<article>
<p>
<Snippet
hit={hit}
attribute="description"
highlightedTagName="strong"
classNames={{
highlighted: 'text-primary font-bold',
}}
/>
</p>
</article>
);
}