Skip to content

Instantly share code, notes, and snippets.

@chronick
Last active May 24, 2017 22:28
Show Gist options
  • Save chronick/a3c8a421581ac682fb857c95ce7e80f3 to your computer and use it in GitHub Desktop.
Save chronick/a3c8a421581ac682fb857c95ce7e80f3 to your computer and use it in GitHub Desktop.
import React from 'react';
/* Usage:
<FuzzyHighlighter query="some" text="something"/>
*/
const FuzzyHighlighter = ({ className, query = '', text = '' }) => {
let lastIdx = 0;
let tSearch = text.toLowerCase();
const indices = query.toLowerCase().split('')
.map((c) => {
let idx = tSearch.indexOf(c, lastIdx);
if (idx > -1) {
lastIdx++;
return idx;
}
return null;
})
.filter((i) => i !== null)
return (
<span>
{ !query.length && text}
{ !!query.length && text.split('').map((tc, i) =>
<span style={{
fontWeight: indices.indexOf(i) > -1 ? 'bold' : 'normal'
}}>
{ tc }
</span>
)}
</span>
)
}
export default FuzzyHighlighter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment