This repository has been archived by the owner on Jul 10, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 323
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add hook to highlight search terms (#333)
- Loading branch information
1 parent
2c9fb73
commit f8b0aa3
Showing
2 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { useEffect } from "react" | ||
|
||
export const useHighlightSearch = (name: string, query: string) => { | ||
function getHighlightedSearch(text: string) { | ||
const parts = text.split(new RegExp(`(${query})`, "gi")) | ||
|
||
const str: string[] = [] | ||
|
||
for (const part of parts) { | ||
if (part.toLowerCase() === query.toLowerCase()) { | ||
str.push(`<mark class="bg-orange-10">${part}</mark>`) | ||
} else { | ||
str.push(part) | ||
} | ||
} | ||
|
||
return str.join("") | ||
} | ||
|
||
useEffect(() => { | ||
const children = document.getElementsByName(name) | ||
|
||
if (children) { | ||
const childArray = Array.from(children) | ||
for (const child of childArray) { | ||
child.innerHTML = child.innerHTML.replace( | ||
child.innerHTML, | ||
getHighlightedSearch(child.innerText) | ||
) | ||
} | ||
} | ||
}, [query, name]) | ||
} |