I have a React Native App and i have a Search Bar and a FlatList. When I Search something in the SearchBar the text has to be highlighted in the list.
Single string search works fine:
But now when I type "visit hour" neither visit or hour gets highlighted
I am using a function for highlighting the text. SearchBar value is stored as this.state.value and I am passing it as props. The logic I am using inside renderItem of Flatlist is as below
getHighlightedText = text => {
const {value} = this.props
const parts = text.split(new RegExp(`(${value})`, 'gim'));
console.log('split:', parts);
return (
<Text>{parts.map(part => (
part.toLowerCase() === value.toLowerCase()) ?
<Text style = {{backgroundColor: 'red'}}>{part}</Text> :
part)}
</Text>
);
}
return <Text>{getHighlightedText(Desc)}</Text>;
This works fine when I search one word. For Example if my flat list has 2 items - "My Dog" and "Her Cat". If my Search Text is "Dog" then Dog is highlighted in red. But if I Search "M Dog" or "M D" then nothing gets Highlighted. It has to highlight characters rather than words. Please help me fix the code!!!!!
Updated my code
So I will be splitting the search value and then try to highlight for each search text. if I enter "visit hour" its split into "visit" and "hour". For some reason the loop executed only for "visit" and not "hour". Some mistake in my code. I have only added a for loop. Please help!!! :
getHighlightedText = text => {
// search value is split and stored in val array. "list" and "hour"
const val = value.split(' ');
// below my item Description is split based on my search
// terms "visit" n "hour" and then stored in vals array
const vals = val.map(valu => {.
var regex = new RegExp(`(${valu})`, 'gim');
return text.split(regex);
})
// vals is merged into 1 array
const merged = [].concat.apply([], vals);
// below I am looping for each of my search text 1st
// "visit" then "hour"
for (i = 0; i < val.length; i++) {
const l = val[i];
return (
<Text>{merged.map(part => (
part.toLowerCase() === l.toLowerCase()) ?
<Text style = {{backgroundColor: 'red'}}>{part}</Text> :
part
)}
</Text>
);
}
}
// using my getHighlightedText in my renderItem
return <Text>{getHighlightedText(Desc)}</Text>;
Loop is getting terminated because of the return statement. "visit" is highlighted but "hour" is not as the loop never reached "hour".
Help please!!!