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

feat: add hook to highlight search terms #333

Merged
merged 5 commits into from
Feb 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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])
}