I am developing a search function in my React project. In the beginning, I only need to input one keyword and search for it in the text, save the sentences with this keyword and display the result sentences separately. I am using "react-highlight-words" https://github.com/bvaughn/react-highlight-words to highlight this single keyword in all the search result sentences.
{searchResults.map((result, idx) => {
return (
<div key={`search-result-${idx}`}>
<br />
<Highlighter
highlightClassName='YourHighlightClass'
searchWords={[textForSearch]}
autoEscape={true}
textToHighlight={finalResults[idx]}
key={idx}
/>
</div>
</div>
);
})}
above textForSearch
is the keyword finalResults
is the search result.
I use a keyword to loop through the text and save the match sentences as elements to an array.
But now I need to input multiple keywords in one search and display some sentences or a paragraph containing these keywords and highlight different keywords with different colors.
how can I use this component to do it? and if some other way to do it please tell me. I have seen many topics and answers related to search and highlight but they all highlight different words with the same color.
const Highlight = ({ children, highlightIndex }) => (
<span className={`highlighted-text keyword-${highlightword.indexOf(children)}`}>{children}</span>
);
and add tag - highlightTag={Highlight}