Home  >  Article  >  Web Front-end  >  How to implement search keyword highlighting in react

How to implement search keyword highlighting in react

藏色散人
藏色散人Original
2022-12-30 13:50:312685browse

How to highlight search keywords in react: 1. Use regular rules to match keywords from the list, and then use tags to contain keywords; 2. Add the color attribute to the tag, and then use react rich text rendering. Rendering enables fast search and keyword highlighting.

How to implement search keyword highlighting in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to highlight search keywords in react?

React implements fast search and keyword highlighting

Requirements:

Click the search button to pop up the fuzzy matching list.

Select an option from the drop-down list and click to jump to the keyword location of the corresponding page.

Idea:

Use regular rules to match keywords from the list, then use labels to contain keywords,

Add color attributes to labels, and use react Render with rich text rendering

js content:

 /**
     * 关键字变色
     * @params content 内容
     * @params keyword 关键词
     * @params tagName 标签名
    */
    warpTag(content, keyword, tagName) {
      if (content === "No results") {
        return content
      }
      const a = content.toLowerCase()
      const b = keyword.toLowerCase()
      const indexof = a.indexOf(b)
      const c = indexof > -1 ? content.substr(indexof, keyword.length) : ''
      const val = `<${tagName} style="color:#FF6600;">${c}</${tagName}>`
      const regS = new RegExp(keyword, &#39;gi&#39;)
      console.log(&#39;regS&#39;,regS,keyword,val)
      console.log(&#39;regS222222&#39;,content,content.replace(regS, val))
      return content.replace(regS, val)
    }

jsx content:

<span dangerouslySetInnerHTML={{__html: this.warpTag(item.n, keyword, "span")}}></span>

Recommended learning: "react video tutorial"

The above is the detailed content of How to implement search keyword highlighting in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn