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?

More than 1 year has passed since last update.

<next.js>storybookでuseParamsを使いたい

Posted at

前提
next.js v13.4 (app router)
storybook v7.4

.storybook/main.ts
import type { StorybookConfig } from '@storybook/nextjs'
import { join, dirname } from 'path'

function getAbsolutePath(value: string): any {
  return dirname(require.resolve(join(value, 'package.json')))
}
const config: StorybookConfig = {
  stories: [
    '<components path>/**/*.stories.@(js|jsx|mjs|ts|tsx)',
  ],
  addons: [
    getAbsolutePath('@storybook/addon-links'),
    getAbsolutePath('@storybook/addon-essentials'),
    getAbsolutePath('@storybook/addon-onboarding'),
    getAbsolutePath('@storybook/addon-interactions'),
  ],
  framework: {
    name: getAbsolutePath('@storybook/nextjs'),
    options: {},
  },
  docs: {
    autodocs: 'tag',
  },
}
export default config

デフォルトではuseParamsを使うコンポーネントをStorybookでレンダリングしたところ取得できない。

やり方

parametersにnextjs用の設定を追加すれば良い。
自分の例ではhttps://example.com/[locale]/hoge のように [locale]部分が動的に切り替わりここを取得したかったのでsegmentsで書いてあげればよかった。

.storybook/previewtsx
const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
    // 追加
    nextjs: {
      appDirectory: true,
      navigation: {
        segments: [['locale', 'ja']],
      },
    },
  },
}

他にもpathの指定やqueryの指定もできる。詳しくは公式を参照してください。

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?