26 lines
No EOL
655 B
JavaScript
26 lines
No EOL
655 B
JavaScript
import { useRouter } from 'next/router'
|
|
import Link from 'next/link'
|
|
import React from 'react'
|
|
|
|
function isActive(linkHref, currentPath) {
|
|
if (linkHref === currentPath) return true;
|
|
const candidateHref = linkHref + '/';
|
|
return candidateHref === currentPath.substring(0, candidateHref.length)
|
|
}
|
|
|
|
function ActiveLink(props) {
|
|
const router = useRouter()
|
|
|
|
const child = props.children
|
|
const childProps = {
|
|
className: child.props.className + ' ' + (isActive(props.href, router.asPath) ? props.activeClassName : ''),
|
|
}
|
|
|
|
return (
|
|
<Link {...props}>
|
|
{React.cloneElement(child, childProps)}
|
|
</Link>
|
|
)
|
|
}
|
|
|
|
export default ActiveLink |