Utility to format matching fuse.js results for easier text highlighting.
yarn add format-fuse.js
The utility expects fuse.js search results as an array and outputs matching text based on matching indices.
import format from "format-fuse.js";
const results = format([
{
item: {
title: "Monster 1959",
author: { firstName: "David", lastName: "Maine" },
},
matches: [
{
indices: [[1, 2]],
value: "Monster 1959",
key: "title",
arrayIndex: 0,
},
],
},
]);
console.log(results);
/**
* [
{
author: { firstName: 'David', lastName: 'Maine' },
title: [
{ matches: false, text: 'M' },
{ matches: true, text: 'on' },
{ matches: false, text: 'ster 1959' }
]
}
]
*/
Matching and unmatching text become easier to iterate through.
import * as React from "react";
export function Highlighter(results) {
return (
<div>
{results.map(({ title }) => {
if (Array.isArray(title)) {
return title.map(({ matches, text }) => {
return matches ? <mark>{text}</mark> : text;
});
}
return title;
})}
</div>
);
}