文字列

useGT と getGT を使ってプレーンテキストの文字列を国際化する方法

文字列の翻訳は、JSX を使わずにテキストの訳文へ直接アクセスでき、属性、オブジェクトのプロパティ、プレーンテキストの値に最適です。同期コンポーネントでは useGT、非同期コンポーネントでは getGT を使用します。

同期 vs 非同期の使い方

  • 同期コンポーネント: React コンポーネント用の useGT フック
  • 非同期コンポーネント: 非同期コンポーネント用の getGT の非同期関数

クイックスタートガイド

同期的コンポーネント

import { useGT } from 'gt-next';

function MyComponent() {
  const t = useGT();
  return (
    <input 
      placeholder={t('メールアドレスを入力')}
      title={t('メールアドレス入力フィールド')}
    />
  );
}

非同期コンポーネント

import { getGT } from 'gt-next/server';

async function MyServerComponent() {
  const t = await getGT();
  return (
    <input 
      placeholder={t('メールアドレスを入力')}
      title={t('メールアドレス入力欄')}
    />
  );
}

文字列翻訳を使うべきタイミング

JSX ではなくプレーンテキストが必要な場合に、文字列翻訳が最適です。

HTML 属性

const t = useGT();

<input 
  placeholder={t('商品を検索...')}
  aria-label={t('商品検索入力')}
  title={t('カタログを検索するには入力してください')}
/>

オブジェクトのプロパティ

const t = useGT();

const user = {
  name: 'John',
  role: 'admin',
  bio: t('React経験5年の熟練ソフトウェア開発者'),
  status: t('現在プロジェクト対応可能')
};

構成と定数

const t = useGT();

const navigationItems = [
  { label: t('ホーム'), href: '/' },
  { label: t('製品'), href: '/products' },
  { label: t('お問い合わせ'), href: '/contact' }
];

<T> を使うタイミング

JSX コンテンツには <T> コンポーネント を使用します。

// ✅ JSXコンテンツには<T>を使用
<T><p><strong>私たちのストア</strong>へようこそ!</p></T>

// ✅ プレーンテキストには文字列翻訳を使用
<input placeholder={t('商品を検索')} />

Variable の使用

基本の変数

プレースホルダーを動的な値に置き換えます:

const t = useGT();
const itemCount = 5;

// プレースホルダー付きの文字列
const message = t('カートに{count}個のアイテムがあります', { count: itemCount });
// 結果: "カートに5個のアイテムがあります"

複数のVariable

const t = useGT();
const order = { id: 'ORD-123', total: 99.99, date: '2024-01-15' };

const confirmation = t(
  '注文 {orderId} の ${total} を {date} に承りました',
  { 
    orderId: order.id, 
    total: order.total, 
    date: order.date 
  }
);

ICUメッセージフォーマット

高度なフォーマットには、ICUの構文を使用します。

const t = useGT();
translate('カートに{count, plural, =0 {商品がありません} =1 {商品が1つあります} other {商品が{count}個あります}}', { count: 10 });

ICU message format の詳細は、Unicode のドキュメントをご覧ください。

フォーム入力項目

import { useGT } from 'gt-next';

function ContactForm() {
  const t = useGT();
  
  return (
    <form>
      <input 
        type="email"
        placeholder={t('メールアドレスを入力')}
        aria-label={t('メール入力欄')}
      />
      <textarea 
        placeholder={t('プロジェクトについてお聞かせください...')}
        aria-label={t('プロジェクト概要')}
      />
      <button type="submit">
        {t('送信')}
      </button>
    </form>
  );
}

ナビゲーション メニュー

import { useGT } from 'gt-next';

function Navigation() {
  const t = useGT();
  
  const menuItems = [
    { label: t('ホーム'), href: '/', icon: 'home' },
    { label: t('会社概要'), href: '/about', icon: 'info' },
    { label: t('サービス'), href: '/services', icon: 'briefcase' },
    { label: t('お問い合わせ'), href: '/contact', icon: 'mail' }
  ];

  return (
    <nav>
      {menuItems.map((item) => (
        <a key={item.href} href={item.href} title={item.label}>
          <Icon name={item.icon} />
          {item.label}
        </a>
      ))}
    </nav>
  );
}

動的コンテンツファクトリ

// utils/productData.js
export function getProductMessages(t) {
  return {
    categories: [
      { id: 'electronics', name: t('電子機器') },
      { id: 'clothing', name: t('衣類') },
      { id: 'books', name: t('書籍') }
    ],
    statusMessages: {
      available: t('在庫あり・発送準備完了'),
      backordered: t('現在取り寄せ中 - 2〜3週間で発送'),  
      discontinued: t('この商品は販売終了いたしました')
    },
    errors: {
      notFound: t('商品が見つかりません'),
      outOfStock: t('申し訳ございません。この商品は現在在庫切れです')
    }
  };
}

// components/ProductCard.jsx
import { useGT } from 'gt-next';
import { getProductMessages } from '../utils/productData';

function ProductCard({ product }) {
  const t = useGT();
  const messages = getProductMessages(t);
  
  return (
    <div>
      <h3>{product.name}</h3>
      <p>{messages.statusMessages[product.status]}</p>
      <span>{messages.categories.find(c => c.id === product.categoryId)?.name}</span>
    </div>
  );
}

メタデータを含む Server Component

import { getGT } from 'gt-next/server';

export async function generateMetadata({ params }) {
  const t = await getGT();
  
  return {
    title: t('商品カタログ - お探しの商品を見つけよう'),
    description: t('厳選された高品質商品の豊富なコレクションをご覧ください'),
    openGraph: {
      title: t('商品を見る'),
      description: t('人気商品のお得な情報をチェック')
    }
  };
}

export default async function ProductPage() {
  const t = await getGT();
  
  return (
    <div>
      <h1>{t('おすすめ商品')}</h1>
      <p>{t('最新の人気アイテムをチェックしてください')}</p>
    </div>
  );
}

よくある問題点

実行時の動的コンテンツ

文字列はビルド時に判明している必要があり、実行時に生成される動的コンテンツは翻訳できません。

// ❌ 動的コンテンツは動作しません
function MyComponent() {
  const [userMessage, setUserMessage] = useState('');
  const t = useGT();
  
  return <p>{t(userMessage)}</p>; // これは失敗します
}

// ✅ 事前定義された文字列を使用
function MyComponent() {
  const [messageType, setMessageType] = useState('welcome');
  const t = useGT();
  
  const messages = {
    welcome: t('アプリへようこそ!'),
    goodbye: t('ご利用ありがとうございました!')
  };
  
  return <p>{messages[messageType]}</p>;
}

Hook ルールの違反

useGT を使用する際は、React のフックのルールに従ってください。

// ❌ フックを条件付きで呼び出してはいけません
function MyComponent({ showMessage }) {
  if (showMessage) {
    const t = useGT(); // フックルール違反
    return <p>{t('こんにちは!')}</p>;
  }
  return null;
}

// ✅ 常にフックをトップレベルで呼び出す
function MyComponent({ showMessage }) {
  const t = useGT();
  
  if (showMessage) {
    return <p>{t('こんにちは!')}</p>;
  }
  return null;
}

同期と非同期の混同

コンポーネントの種類に合った関数を使いましょう。

// ❌ 間違い: 非同期コンポーネントでuseGTを使用
export default async function AsyncComponent() {
  const t = useGT(); // これは動作しません
  return <p>{t('Hello')}</p>;
}

// ✅ 正しい: 非同期コンポーネントでgetGTを使用  
export default async function AsyncComponent() {
  const t = await getGT();
  return <p>{t('Hello')}</p>;
}

// ✅ 正しい: 同期コンポーネントでuseGTを使用
export default function SyncComponent() {
  const t = useGT();
  return <p>{t('Hello')}</p>;
}

実行時に翻訳が必要な真に動的なコンテンツについては、Dynamic Content Guideをご参照ください。

次のステップ

このガイドはどうでしたか?

文字列