Skip to content
This repository has been archived by the owner on Jul 10, 2023. It is now read-only.

Commit

Permalink
feat: add hook to highlight search terms (#333)
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperkristensen authored Feb 14, 2022
1 parent 2c9fb73 commit f8b0aa3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/components/molecules/table/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type TablePaginationProps = React.HTMLAttributes<HTMLDivElement> & {

type TableCellProps = React.HTMLAttributes<HTMLTableCellElement> & {
linkTo?: string
name?: string
}

type SortingHeadCellProps = {
Expand Down
33 changes: 33 additions & 0 deletions src/hooks/use-highlight-search.tsx
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])
}

0 comments on commit f8b0aa3

Please sign in to comment.