Created
January 26, 2021 19:11
-
-
Save ricokareem/52e04a1eab9a72402945267095a50924 to your computer and use it in GitHub Desktop.
[React] Highlight search string matches in results without dangerouslySetInnerHTML
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
// Highlight search string matches in results | |
const HighlightedResults = (): JSX.Element | null => { | |
if (inputValue) { | |
const match = item.name.match(new RegExp(inputValue, 'i')) | |
const MatchEl = (): ReactElement | null => { | |
if (match && match.length) { | |
return <strong>{match[0]}</strong> | |
} else { | |
return null | |
} | |
} | |
const rest = item.name.split(new RegExp(inputValue, 'i')) | |
return ( | |
<> | |
{rest.map((x: string, index: number) => { | |
if (index !== rest.length - 1) { | |
return ( | |
<span key={index}> | |
{x} | |
<MatchEl /> | |
</span> | |
) | |
} else { | |
return <span key={index}>{x}</span> | |
} | |
})} | |
</> | |
) | |
} else { | |
return <>{item.name}</> | |
} | |
} | |
. | |
. | |
. | |
. | |
<HighlightedResults /> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment