Skip to content

Instantly share code, notes, and snippets.

@loopmode
Created March 18, 2021 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loopmode/6bada86f518f5bdd82828694986d7d89 to your computer and use it in GitHub Desktop.
Save loopmode/6bada86f518f5bdd82828694986d7d89 to your computer and use it in GitHub Desktop.
react highlight words
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