1
1
import { useRouter } from 'next/router'
2
2
import Link , { LinkProps } from 'next/link'
3
- import React , { useState , useEffect , ReactElement , Children } from 'react'
3
+ import React , { PropsWithChildren , useState , useEffect } from 'react'
4
4
5
5
type ActiveLinkProps = LinkProps & {
6
- children : ReactElement
6
+ className ?: string
7
7
activeClassName : string
8
8
}
9
9
10
10
const ActiveLink = ( {
11
11
children,
12
12
activeClassName,
13
+ className,
13
14
...props
14
- } : ActiveLinkProps ) => {
15
+ } : PropsWithChildren < ActiveLinkProps > ) => {
15
16
const { asPath, isReady } = useRouter ( )
16
-
17
- const child = Children . only ( children )
18
- const childClassName = child . props . className || ''
19
- const [ className , setClassName ] = useState ( childClassName )
17
+ const [ computedClassName , setComputedClassName ] = useState ( className )
20
18
21
19
useEffect ( ( ) => {
22
20
// Check if the router fields are updated client-side
@@ -33,29 +31,26 @@ const ActiveLink = ({
33
31
34
32
const newClassName =
35
33
linkPathname === activePathname
36
- ? `${ childClassName } ${ activeClassName } ` . trim ( )
37
- : childClassName
34
+ ? `${ className } ${ activeClassName } ` . trim ( )
35
+ : className
38
36
39
- if ( newClassName !== className ) {
40
- setClassName ( newClassName )
37
+ if ( newClassName !== computedClassName ) {
38
+ setComputedClassName ( newClassName )
41
39
}
42
40
}
43
41
} , [
44
42
asPath ,
45
43
isReady ,
46
44
props . as ,
47
45
props . href ,
48
- childClassName ,
49
46
activeClassName ,
50
- setClassName ,
51
47
className ,
48
+ computedClassName ,
52
49
] )
53
50
54
51
return (
55
- < Link { ...props } legacyBehavior >
56
- { React . cloneElement ( child , {
57
- className : className || null ,
58
- } ) }
52
+ < Link className = { computedClassName } { ...props } >
53
+ { children }
59
54
</ Link >
60
55
)
61
56
}
0 commit comments