Created
March 18, 2021 06:47
-
-
Save loopmode/6bada86f518f5bdd82828694986d7d89 to your computer and use it in GitHub Desktop.
react highlight words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import escapeRegExp from 'lodash.escaperegexp'; | |
// based on https://stackoverflow.com/a/47803998/368254 | |
export function Highlighted({ children: 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) ? ( | |
<b key={i}>{part}</b> | |
) : ( | |
<span key={i}>{part}</span> | |
) | |
)} | |
</span> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment