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!!!!!

rakshahegde10 Default Asked on September 17, 2023 in Computer.
Add Comment
  • 0 Answer(s)
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.