-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathHighlightedText.tsx
More file actions
52 lines (46 loc) · 1.09 KB
/
HighlightedText.tsx
File metadata and controls
52 lines (46 loc) · 1.09 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'use client';
import { Text } from '@mantine/core';
import { useMemo } from 'react';
interface HighlightedTextProps {
text: string;
highlight: string;
highlightColor?: string;
}
export default function HighlightedText({
text,
highlight,
highlightColor = '#fff3cd',
}: HighlightedTextProps) {
const parts = useMemo(() => {
if (!highlight.trim()) {
return [{ text, isHighlight: false }];
}
const regex = new RegExp(`(${highlight.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
const splitText = text.split(regex);
return splitText.map((part) => ({
text: part,
isHighlight: regex.test(part),
}));
}, [text, highlight]);
return (
<>
{parts.map((part, i) =>
part.isHighlight ? (
<Text
key={i}
component="mark"
style={{
backgroundColor: highlightColor,
padding: '0 2px',
borderRadius: 2,
}}
>
{part.text}
</Text>
) : (
<span key={i}>{part.text}</span>
)
)}
</>
);
}