Skip to content

Commit

Permalink
feat(highlighter): allow mark element to be customized (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
lindapaiste authored Feb 8, 2022
1 parent 60f5e3d commit 5adac81
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/Highlighter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import * as React from 'react';

function Highlighter(props: IHighlighterProps) {
if (Array.isArray(props.text)) {
const Mark = props.mark || 'mark';
return (
<>
{props.text.map(({ text, isHighlighted }, index) => {
const key = `${text}${index}`; // TODO: generate id

if (isHighlighted) {
// TODO: allow custom highlight element
return <mark key={key}>{text}</mark>;
return <Mark key={key}>{text}</Mark>;
}

return <React.Fragment key={key}>{text}</React.Fragment>;
Expand All @@ -22,7 +22,16 @@ function Highlighter(props: IHighlighterProps) {
}

interface IHighlighterProps {
/**
* The text to display.
* Either a `string` or an array of formatted results from the FuzzyHighlighter.
*/
text: string | { text: string; isHighlighted: boolean }[];
/**
* Custom JSX element to surround highlighted text.
* Default: 'mark'
*/
mark?: keyof JSX.IntrinsicElements | React.ComponentType;
}

export { Highlighter };
16 changes: 16 additions & 0 deletions src/tests/Highlighter.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,20 @@ describe("Highlighter", () => {
const wrapper = shallow(<Highlighter text={"Old"} />);
expect(wrapper.html()).toEqual("Old");
});

test("prop `mark` as a custom component", () => {
const Mark: React.FC = ({children}) => (
<span className="marked-text">{children}</span>
);
const wrapper = shallow(
<Highlighter
text={[
{ text: "O", isHighlighted: true },
{ text: "ld", isHighlighted: false },
]}
mark={Mark}
/>
);
expect(wrapper.html()).toEqual("<span class=\"marked-text\">O</span>ld");
});
});

0 comments on commit 5adac81

Please sign in to comment.