简体   繁体   中英

how to use react-highlight-words to highlight multiple keywords with different colors

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} );

and add tag - highlightTag={Highlight}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM