Skip to content

Instantly share code, notes, and snippets.

@ricokareem
Created January 26, 2021 19:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricokareem/52e04a1eab9a72402945267095a50924 to your computer and use it in GitHub Desktop.
Save ricokareem/52e04a1eab9a72402945267095a50924 to your computer and use it in GitHub Desktop.
[React] Highlight search string matches in results without dangerouslySetInnerHTML
// 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