-
Notifications
You must be signed in to change notification settings - Fork 70
/
index.js
48 lines (44 loc) · 1.4 KB
/
index.js
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
import React from 'react';
import {Text} from 'react-native';
import {findAll} from 'highlight-words-core';
import PropTypes from 'prop-types';
Highlighter.propTypes = {
autoEscape: PropTypes.bool,
highlightStyle: Text.propTypes.style,
searchWords: PropTypes.arrayOf(PropTypes.string).isRequired,
textToHighlight: PropTypes.string.isRequired,
sanitize: PropTypes.func,
style: Text.propTypes.style
};
/**
* Highlights all occurrences of search terms (searchText) within a string (textToHighlight).
* This function returns an array of strings and <Text> elements (wrapping highlighted words).
*/
export default function Highlighter({
autoEscape,
highlightStyle,
searchWords,
textToHighlight,
sanitize,
style,
...props
}) {
const chunks = findAll({textToHighlight, searchWords, sanitize, autoEscape});
return (
<Text style={style} {...props}>
{chunks.map((chunk, index) => {
const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start);
return (!chunk.highlight)
? text
: (
<Text
key={index}
style={chunk.highlight && highlightStyle}
>
{text}
</Text>
);
})}
</Text>
);
}