How to implement search keyword highlighting in react

藏色散人
Release: 2022-12-30 13:50:31
Original
2822 people have browsed it

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)
    }
Copy after login

jsx content:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!