Next.js(next/link)にて、現在のページにアクティブクラス(active class)を設定する方法になります。
ナビゲーションなので、ルートと一致するリンクのスタイルを変えたい時に便利かと思います。
(Vue.jsのactive-classのイメージです)
Active Link componentsを作成
ActiveLink.tsx
import { withRouter } from 'next/router'
import Link from 'next/link'
import React, { Children } from 'react'
const ActiveLink = ({ router, children, ...props }: any) => {
const child = Children.only(children)
let className = child.props.className || ''
if (router.pathname === props.href && props.activeClassName) {
className = `${className} ${props.activeClassName}`.trim()
}
delete props.activeClassName
return <Link {...props}>{React.cloneElement(child, { className })}</Link>
}
export default withRouter(ActiveLink)
next/link
には、デフォルトでアクティブクラスをつける機能は無いので、next/link
をラップして新たなcomponentsを作ります。
作成したActive Link componentsを読み込む
import ActiveLink from '../components/common/ActiveLink'
const Home = () => {
return (
<div>
<ActiveLink href="/" activeClassName="bg-red-200"> // ルートが一致した時のstyle(active class)
<a className="p-2">Home</a> // 共通のスタイル
</ActiveLink>
<ActiveLink href="/demo" activeClassName="bg-red-200">
<a className="p-2">Demo</a>
</ActiveLink>
<ActiveLink href="/demo2" activeClassName="bg-red-200">
<a className="p-2">Demo2</a>
</ActiveLink>
</div>
)
}
export default Home
上記で作成したActiveLink.tsx
を使用します。
activeClassName
にアクティブクラスを設定することができます。
参考