forked from algolia/docsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnippet.tsx
More file actions
33 lines (28 loc) · 808 Bytes
/
Snippet.tsx
File metadata and controls
33 lines (28 loc) · 808 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { type JSX, createElement } from 'react';
import type { StoredDocSearchHit } from './types';
function getPropertyByPath(object: Record<string, any>, path: string): any {
const parts = path.split('.');
return parts.reduce((prev, current) => {
if (prev?.[current]) return prev[current];
return null;
}, object);
}
interface SnippetProps<TItem> {
hit: TItem;
attribute: string;
tagName?: string;
[prop: string]: unknown;
}
export function Snippet<TItem extends StoredDocSearchHit>({
hit,
attribute,
tagName = 'span',
...rest
}: SnippetProps<TItem>): JSX.Element {
return createElement(tagName, {
...rest,
dangerouslySetInnerHTML: {
__html: getPropertyByPath(hit, `_snippetResult.${attribute}.value`) || getPropertyByPath(hit, attribute),
},
});
}