1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsで現在のページと一致した時にナビゲーションリンクのスタイルをStorybookで表現したい

Posted at

現在のページパスと一致したときにナビゲーションリンクを変更したい場合があります。
実装はできてもStorybookにはどうやって反映させるんだ?となったのでTipsとして残します!

現在のページの判定方法は?

Sotrybookへの反映方法を知りたい方が記事を読んでいると思うので説明不要な部分だと思いますが…。
それも一緒に知りたかった!って方のためにサラッと書いておきます!

Next.jsを利用していればusePathnameを利用できます!

下記利用方法の例を記載しておきましたので参考にしてください!

import { usePathname } from 'next/navigation'

export const Component = ({
  href,
  text,
}) => {
  const pathname = usePathname()
  const active = pathname === href

  return (
    <a href={href} className={active ? 'red' : 'black'}>
      {text}
    </a>
  )
}

次に本題のStorybookの書き方について説明します!

Storyの定義部分にてparameterspathを渡してあげる!

下記の記事をそのまま流用しました!

export const Default: Story = {
  parameters: {
    nextjs: {
      appDirectory: true,
      navigation: {
        pathname: '/top/hoge/',
      },
    },
  },
  args: {...}

補足説明

appDirectory: true,の部分はStorybookのpreview.(js|ts|tsx)に記載してあればこちらで指定する必要はありません。

プロジェクトにpagesディレクトリがない構成であればpreview.(js|ts|tsx)に記載してあると思いますので確認してください!

まとめ

調べる前は少し複雑なことを考えてしまってましたが、Storybookが用意してくれてました!
皆さんのStorybookがより良いものになることを祈っております!

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?