文字列

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

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

クイックスタート

import { useGT } from 'gt-react';

function MyComponent() {
  const t = useGT();
  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('商品を検索')} />

変数の使用

基本のvariables

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

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

// プレースホルダーを含む文字列
const message = t('カートに{count}件の商品があります', { count: itemCount });
// 結果: "カートに5件の商品があります"

複数のvariables

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-react';

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-react';

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>
  );
}

Dynamic Content Factory(動的コンテンツファクトリ)

// 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-react';
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>
  );
}

ドキュメントタイトル付きコンポーネント

import { useGT } from 'gt-react';
import { useEffect } from 'react';

function ProductPage() {
  const t = useGT();
  
  useEffect(() => {
    document.title = t('製品カタログ — 必要なものが見つかります');
    
    // Update meta description
    const metaDescription = document.querySelector('meta[name="description"]');
    if (metaDescription) {
      metaDescription.setAttribute('content', t('高品質な製品を豊富に取り揃えています'));
    }
  }, [t]);
  
  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>;
}

フック規則違反

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;
}

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

次のステップ

このガイドはいかがですか?