Skip to content

Commit 23e71ce

Browse files
authored
docs(example): add example of Highlight implemented in React (#848)
1 parent 9640c2d commit 23e71ce

File tree

2 files changed

+43
-7
lines changed

2 files changed

+43
-7
lines changed

examples/react-renderer/src/Autocomplete.tsx

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { Hit } from '@algolia/client-search';
88
import algoliasearch from 'algoliasearch/lite';
99
import React from 'react';
1010

11+
import { Highlight } from './Highlight';
1112
import { ClearIcon } from './ClearIcon';
1213
import { SearchIcon } from './SearchIcon';
1314

@@ -63,8 +64,6 @@ export function Autocomplete(
6364
query,
6465
params: {
6566
hitsPerPage: 5,
66-
highlightPreTag: '<mark>',
67-
highlightPostTag: '</mark>',
6867
},
6968
},
7069
],
@@ -173,11 +172,9 @@ export function Autocomplete(
173172
<div className="aa-ItemContentBody">
174173
<div
175174
className="aa-ItemContentTitle"
176-
dangerouslySetInnerHTML={{
177-
__html: item._highlightResult!.name!
178-
.value,
179-
}}
180-
/>
175+
>
176+
<Highlight hit={item} attribute="name" />
177+
</div>
181178
<div className="aa-ItemContentDescription">
182179
By <strong>{item.brand}</strong> in{' '}
183180
<strong>{item.categories[0]}</strong>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { createElement, Fragment } from "react";
2+
import { parseAlgoliaHitHighlight } from "@algolia/autocomplete-preset-algolia";
3+
4+
type HighlightHitParams<THit> = {
5+
/**
6+
* The Algolia hit whose attribute to retrieve the highlighted parts from.
7+
*/
8+
hit: THit;
9+
/**
10+
* The attribute to retrieve the highlighted parts from.
11+
*
12+
* You can use the array syntax to reference nested attributes.
13+
*/
14+
attribute: keyof THit | string[];
15+
/**
16+
* The tag name to use for highlighted parts.
17+
*
18+
* @default "mark"
19+
*/
20+
tagName?: string;
21+
};
22+
23+
export function Highlight<THit>({
24+
hit,
25+
attribute,
26+
tagName = "mark",
27+
}: HighlightHitParams<THit>): JSX.Element {
28+
return createElement(
29+
Fragment,
30+
{},
31+
parseAlgoliaHitHighlight<THit>({ hit, attribute }).map(
32+
({ value, isHighlighted }, index) => {
33+
if (isHighlighted) return createElement(tagName, { key: index }, value);
34+
35+
return value;
36+
}
37+
)
38+
);
39+
}

0 commit comments

Comments
 (0)