2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Storybook で next-intl の言語切り替えや useTlanslations を動かすためのメモ

Posted at

Storybook を用いて開発を行うときに詰まったので忘備録。

前提として

  • nextjs / app router
  • next-intl
  • storybook

という構成。

要点は

  • NextIntlClientProvider を使うこと
  • useMessage を使わずに自前で message を組み立てること
  • 自前で locale の設定を行える口を作る

の2点である。
useMessage が 動かないので、本体の開発と同じノリでやると失敗するので注意。
なので decorator で NextIntlClientProvider を使う.

また、locale の値を通すために globalType を経由して設定する。
こうすることでおそらく開発可能。

RSC でも挙動を確認できたので多分大丈夫。

import type { Preview } from '@storybook/react';
import React, { useEffect } from 'react';
import { NextIntlClientProvider } from 'next-intl';
import ja from '../src/locales/ja.json';
import en from '../src/locales/en.json';

const withIntl = (Story, context) => {
  const locale = context.globals.locale;

  return (
    <NextIntlClientProvider locale={locale} messages={locale === 'ja' ? ja : en}>
      <Story />
    </NextIntlClientProvider>
  );
};

export const globalTypes = {
  locale: {
    name: 'Locale',
    description: 'Internationalization locale',
    defaultValue: 'ja',
    toolbar: {
      icon: 'globe',
      items: [
        { value: 'ja', title: '日本語' },
        { value: 'en', title: 'English' },
      ],
      showName: true,
    },
  },
};

const preview: Preview = {
  parameters: {
    nextjs: {
      appDirectory: true,
    },
  },
  decorators: [withIntl],
};

export default preview;
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?