/
ActiveLink.tsx
63 lines (54 loc) · 1.51 KB
/
ActiveLink.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { useRouter } from 'next/router'
import Link, { LinkProps } from 'next/link'
import React, { useState, useEffect, ReactElement, Children } from 'react'
type ActiveLinkProps = LinkProps & {
children: ReactElement
activeClassName: string
}
const ActiveLink = ({
children,
activeClassName,
...props
}: ActiveLinkProps) => {
const { asPath, isReady } = useRouter()
const child = Children.only(children)
const childClassName = child.props.className || ''
const [className, setClassName] = useState(childClassName)
useEffect(() => {
// Check if the router fields are updated client-side
if (isReady) {
// Dynamic route will be matched via props.as
// Static route will be matched via props.href
const linkPathname = new URL(
(props.as || props.href) as string,
location.href
).pathname
// Using URL().pathname to get rid of query and hash
const activePathname = new URL(asPath, location.href).pathname
const newClassName =
linkPathname === activePathname
? `${childClassName} ${activeClassName}`.trim()
: childClassName
if (newClassName !== className) {
setClassName(newClassName)
}
}
}, [
asPath,
isReady,
props.as,
props.href,
childClassName,
activeClassName,
setClassName,
className,
])
return (
<Link {...props} legacyBehavior>
{React.cloneElement(child, {
className: className || null,
})}
</Link>
)
}
export default ActiveLink