rsnext/examples/active-class-name/components/ActiveLink.js
Aubrey 7d8e0c512f
updated active-class-name example to also demo a [slug] path (#15924)
updated example for [active-class-name](f00ad581a1/examples/active-class-name) to also support a `[slug].js` page that matches on `as` instead of `href` (as `href` would be `/[slug]`)

> This does not demo `[..slug].js` as this requires possible custom code for determining the slug path part for the active classname. i.e. page tree active nodes. A possible other example or another PR on this example.

Has possible information for:
 * https://github.com/vercel/next.js/issues/7410
2020-08-06 01:26:48 +00:00

32 lines
874 B
JavaScript

import { useRouter } from 'next/router'
import PropTypes from 'prop-types'
import Link from 'next/link'
import React, { Children } from 'react'
const ActiveLink = ({ children, activeClassName, ...props }) => {
const { asPath } = useRouter()
const child = Children.only(children)
const childClassName = child.props.className || ''
// pages/index.js will be matched via props.href
// pages/about.js will be matched via props.href
// pages/[slug].js will be matched via props.as
const className =
asPath === props.href || asPath === props.as
? `${childClassName} ${activeClassName}`.trim()
: childClassName
return (
<Link {...props}>
{React.cloneElement(child, {
className: className || null,
})}
</Link>
)
}
ActiveLink.propTypes = {
activeClassName: PropTypes.string.isRequired,
}
export default ActiveLink