depot/web/lukegbcom/lib/ActiveLink/index.js

26 lines
655 B
JavaScript
Raw Normal View History

2022-04-03 23:32:57 +00:00
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