Files
web/components/TempDesignSystem/Link/index.tsx
2024-08-12 10:26:02 +02:00

70 lines
1.3 KiB
TypeScript

"use client"
import NextLink from "next/link"
import { usePathname } from "next/navigation"
import { useCallback, useEffect } from "react"
import { trackClick } from "@/utils/tracking"
import { linkVariants } from "./variants"
import type { LinkProps } from "./link"
export default function Link({
active,
className,
color,
href,
partialMatch = false,
textDecoration,
size,
scroll = true,
prefetch,
variant,
trackingId,
...props
}: LinkProps) {
const currentPageSlug = usePathname()
let isActive = active || currentPageSlug === href
if (partialMatch && !isActive) {
isActive = currentPageSlug === href
}
const classNames = linkVariants({
active: isActive,
className,
textDecoration,
color,
size,
variant,
})
const trackClickById = useCallback(() => {
if (trackingId) {
trackClick(trackingId)
}
}, [trackingId])
useEffect(() => {
if (trackingId) {
const linkComponent = document.getElementById(trackingId)
linkComponent?.addEventListener("click", trackClickById)
return () => {
linkComponent?.removeEventListener("click", trackClickById)
}
}
}, [trackClickById, trackingId])
return (
<NextLink
scroll={scroll}
prefetch={prefetch}
className={classNames}
href={href}
id={trackingId}
{...props}
/>
)
}