Created
May 26, 2024 13:53
-
-
Save neelabalan/05f91be4f965bc41cadb249bb6c71c0f to your computer and use it in GitHub Desktop.
Text Highlight Componenet
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
// https://stackoverflow.com/a/56786860/4873716 | |
const Highlighter = ({children, highlight}) => { | |
if (!highlight) return children; | |
const regexp = new RegExp(highlight, 'g'); | |
const matches = children.match(regexp); | |
console.log(matches, parts); | |
var parts = children.split(new RegExp(`${highlight.replace()}`, 'g')); | |
for (var i = 0; i < parts.length; i++) { | |
if (i !== parts.length - 1) { | |
let match = matches[i]; | |
// While the next part is an empty string, merge the corresponding match with the current | |
// match into a single <span/> to avoid consequent spans with nothing between them. | |
while(parts[i + 1] === '') { | |
match += matches[++i]; | |
} | |
parts[i] = ( | |
<React.Fragment key={i}> | |
{parts[i]}<span className="highlighted">{match}</span> | |
</React.Fragment> | |
); | |
} | |
} | |
return <div className="highlighter">{parts}</div>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment