翻訳の読み込み

プロバイダーを使用したメッセージ管理

問題

「Hello World」のようなテキストをアプリケーションのコンポーネントに直接ハードコーディングすると、コンテンツとコードが密結合します。異なる言語を表示するには、開発者はコンポーネントを複製するか、if/elseロジックを追加する必要があり、翻訳がスケーラブルでなくなり、新しいテキストごとにコード全体の変更が必要になります。

解決策

react-intlIntlProviderを使用して翻訳を提供します。ルートレイアウトでサーバー上の翻訳メッセージを読み込み、クライアント側のプロバイダーコンポーネントに渡し、useIntlフックを使用して他のクライアントコンポーネントで使用します。

手順

1. react-intlをインストール

まず、react-intlをプロジェクトの依存関係として追加します。

npm install react-intl

2. フラットな翻訳ファイルを作成

dictionariesフォルダーを作成します。その中に、各言語用のJSONファイルを追加します。react-intlは、フラットなキーと値の構造で最適に動作します。

// dictionaries/en.json
{
  "home.title": "Home Page",
  "home.welcome": "Hello, welcome to our site!",
  "about.title": "About Us"
}
// dictionaries/es.json
{
  "home.title": "Página de Inicio",
  "home.welcome": "¡Hola, bienvenido a nuestro sitio!",
  "about.title": "Sobre Nosotros"
}

3. 辞書を読み込む関数を作成

langパラメーターに基づいて、サーバー上で正しい辞書ファイルを読み込むヘルパー関数を作成します。

// app/get-dictionary.ts
import 'server-only';

// Define the type for our flat message object
type Messages = Record<string, string>;

const dictionaries: { [key: string]: () => Promise<Messages> } = {
  en: () => import('@/dictionaries/en.json').then((module) => module.default),
  es: () => import('@/dictionaries/es.json').then((module) => module.default),
  // fr: () => import('@/dictionaries/fr.json').then((module) => module.default),
};

export const getDictionary = async (lang: string) => {
  const load = dictionaries[lang];
  if (load) {
    return load();
  }
  // Fallback to English
  return dictionaries.en();
};

4. クライアント側プロバイダーを作成

IntlProviderは、ReactのContextを使用するクライアントコンポーネントです。サーバーから読み込まれたメッセージを受け取ることができるラッパーを作成する必要があります。

// app/components/IntlClientProvider.tsx
'use client';

import { IntlProvider } from 'react-intl';

type Props = {
  children: React.ReactNode;
  locale: string;
  messages: Record<string, string>; // Flat messages object
};

export default function IntlClientProvider({
  children,
  locale,
  messages,
}: Props) {
  return (
    <IntlProvider messages={messages} locale={locale} defaultLocale="en">
      {children}
    </IntlProvider>
  );
}

5. ルートレイアウトを更新

app/[lang]/layout.tsxasyncコンポーネントに変更します。メッセージを読み込み、IntlClientProviderに渡します。

// app/[lang]/layout.tsx
import { getDictionary } from '@/app/get-dictionary';
import IntlClientProvider from '@/app/components/IntlClientProvider';

export async function generateStaticParams() {
  return [{ lang: 'en' }, { lang: 'es' }];
}

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: { lang: string };
}) {
  // Load messages on the server
  const messages = await getDictionary(params.lang);

  return (
    <html lang={params.lang}>
      <body>
        {/* Pass messages to the client provider */}
        <IntlClientProvider locale={params.lang} messages={messages}>
          {children}
        </IntlClientProvider>
      </body>
    </html>
  );
}

6. クライアントコンポーネントで翻訳を使用する

useIntlフックを任意のクライアントコンポーネントで使用できるようになりました。サーバーコンポーネントではこのフックを使用できません。

翻訳されたテキストを表示する新しいクライアントコンポーネントを作成します。

// app/components/HomePageContent.tsx
'use client';

import { useIntl } from 'react-intl';

export default function HomePageContent() {
  const intl = useIntl();

  return (
    <div>
      <h1>{intl.formatMessage({ id: 'home.title' })}</h1>
      <p>{intl.formatMessage({ id: 'home.welcome' })}</p>
    </div>
  );
}

7. ページにコンポーネントを追加する

最後に、新しいクライアントコンポーネントをページに追加します。

// app/[lang]/page.tsx
import HomePageContent from '@/app/components/HomePageContent';

export default function Home() {
  // This page is a Server Component
  return (
    <div>
      {/* It renders the Client Component */}
      <HomePageContent />
    </div>
  );
}