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.
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, 'gi') console.log('regS',regS,keyword,val) console.log('regS222222',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!