10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.js(next/link)にて、現在のページにアクティブクラス(active class)を設定する方法

Last updated at Posted at 2021-05-02

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

next active class.JPG

上記で作成したActiveLink.tsxを使用します。
activeClassNameにアクティブクラスを設定することができます。

参考

10
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?