Highlight text using ReactJS? Here is an example of a react component that uses the standard tag to highlight a text:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const Highlighted = ({text = '', highlight = ''}) => { if (!highlight.trim()) { return <span>{text}</span> } const regex = new RegExp(`(${_.escapeRegExp(highlight)})`, 'gi') const parts = text.split(regex) return ( <span> {parts.filter(part => part).map((part, i) => ( regex.test(part) ? <mark key={i}>{part}</mark> : <span key={i}>{part}</span> ))} </span> ) } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.