文字列
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('商品を検索')} />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 Message Format
高度なフォーマットには、ICUの構文を使用します:
const t = useGT();
translate('カートに{count, plural, =0 {商品がありません} =1 {商品が1つあります} other {商品が{count}個あります}}', { count: 10 });UnicodeのドキュメントでICU Message Formatの詳細をご確認ください。
例
フォーム入力項目
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>
  );
}動的コンテンツファクトリ
// 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('製品カタログ - 必要なものを見つけましょう');
    
    // メタディスクリプションを更新
    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>;
}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;
}実行時に翻訳が必要な真に動的なコンテンツについては、Dynamic Content Guideを参照してください。
次のステップ
- Dynamic Content Guide - 実行時の翻訳を処理する
- Shared Strings Guide - 再利用可能な翻訳を整理する
- APIリファレンス:
このガイドはどうでしたか?

