# gt-react: General Translation React SDK: 共通文字列
URL: https://generaltranslation.com/ja/docs/react/guides/shared-strings.mdx
---
title: 共通文字列
description: 複数のコンポーネントやファイルで使う文字列を国際化する方法
---
{/* 自動生成: 直接編集しないでください。代わりに content/docs-templates/ 内の template を編集してください。 */}
共通文字列は、アプリケーション内の複数の場所で使われるテキスト値です。たとえば、ナビゲーションラベル、フォームメッセージ、設定データなどがあります。あちこちで翻訳ロジックを重複して書く代わりに、[`msg`](/docs/react/api/strings/msg) を使って文字列を翻訳対象としてマークし、[`useMessages`](/docs/react/api/strings/use-messages) を使ってそれらをデコードします。
## 共有コンテンツの問題点
アプリ全体で使う次のナビゲーション設定を考えてみましょう。
```tsx
// navData.ts
export const navData = [
{
label: 'Home',
description: 'The home page',
href: '/'
},
{
label: 'About',
description: 'Information about the company',
href: '/about'
}
];
```
これを国際化するには、通常は次の作業が必要です。
1. 翻訳関数を受け取る関数に書き換える
2. その関数を `t` を渡して呼び出すよう、すべての使用箇所を更新する
3. コードベース全体にまたがる複雑さに対処する
その結果、保守の負担が増え、コードも読みにくくなります。[`msg`](/docs/react/api/strings/msg) 関数を使えば、文字列をその場で翻訳対象としてマークし、必要になったときにデコードできるため、この問題を解決できます。
## クイックスタート
[`msg`](/docs/react/api/strings/msg) を使って文字列をマークし、[`useMessages`](/docs/react/api/strings/use-messages) でそれらをデコードします。
```tsx
// navData.ts - 翻訳対象の文字列をマークする
import { msg } from 'gt-react';
export const navData = [
{
label: msg('Home'),
description: msg('The home page'),
href: '/'
},
{
label: msg('About'),
description: msg('Information about the company'),
href: '/about'
}
];
```
```tsx
// コンポーネントの使用 - マークされた文字列をデコードする
import { useMessages } from 'gt-react';
import { navData } from './navData';
function Navigation() {
const m = useMessages();
return (
);
}
```
## 共通文字列の動作
共通文字列システムは、2 つのフェーズで動作します:
1. **Mark Phase**: [`msg`](/docs/react/api/strings/msg) は文字列を翻訳メタデータ付きでエンコードします
2. **Decode Phase**: [`useMessages`](/docs/react/api/strings/use-messages) は文字列をデコードして翻訳します
```tsx
// msg() はメタデータとともに文字列をエンコードする
const encoded = msg('Hello, world!');
console.log(encoded); // "Hello, world!:eyIkX2hhc2giOiJkMjA3MDliZGExNjNlZmM2In0="
// useMessages() はデコードして翻訳する
const m = useMessages();
const translated = m(encoded); // ユーザーの言語での "Hello, world!"
```
[`msg`](/docs/react/api/strings/msg) でエンコードされた文字列は直接使用できません。[`useMessages`](/docs/react/api/strings/use-messages) でデコードする必要があります。
## コンポーネント
[`useMessages`](/docs/react/api/strings/use-messages) Hook を使用します:
```tsx
import { useMessages } from 'gt-react';
const encodedString = msg('Hello, world!');
function MyComponent() {
const m = useMessages();
return
{m(encodedString)}
;
}
```
## `decodeMsg`で元の文字列を取得する
ログの記録、デバッグ、比較などで、翻訳せずに元の文字列にアクセスしたい場合があります。元のテキストを取り出すには、[`decodeMsg`](/docs/react/api/strings/msg)を使用します。
```tsx
import { decodeMsg } from 'gt-react';
const encoded = msg('Hello, world!');
const original = decodeMsg(encoded); // "Hello, world!" (元の文字列)
const translated = m(encoded); // "Hello, world!" (ユーザーの言語)
// ログやデバッグに便利
console.log('元の文字列:', decodeMsg(encoded));
console.log('翻訳済み文字列:', m(encoded));
```
### decodeMsg のユースケース
* **開発とデバッグ**: トラブルシューティングのために元の文字列をログに記録する
* **フォールバック処理**: 翻訳に失敗した場合は元のテキストを使用する
* **文字列の比較**: 既知の元の値と比較する
* **アナリティクス**: 元の文字列の使用状況を追跡する
```tsx
// 例: フォールバック処理
function getDisplayText(encodedStr) {
const m = useMessages();
try {
return m(encodedStr);
} catch (error) {
console.warn('翻訳に失敗しました。元の文字列を使用します:', decodeMsg(encodedStr));
return decodeMsg(encodedStr);
}
}
```
## 変数を使う
動的な内容を含む文字列では、プレースホルダーを使用して変数を渡します。
```tsx
// 変数付きの文字列をマークする
const items = 100;
export const pricing = [
{
name: 'Basic',
price: 100,
description: msg('The basic plan includes {items} items', { items })
}
];
```
```tsx
// コンポーネントで使用
function PricingCard() {
const m = useMessages();
return (
{pricing[0].name}
{m(pricing[0].description)}
);
}
```
### ICU メッセージ形式
より高度な書式設定には、ICU 構文を使用します。
```tsx
const count = 10;
const message = msg('There are {count, plural, =0 {no items} =1 {one item} other {{count} items}} in the cart', { count });
```
ICU メッセージ形式について詳しくは、[Unicode ドキュメント](https://unicode-org.github.io/icu/userguide/format_parse/messages/)を参照してください。
## 例
### ナビゲーション設定
```tsx
// config/navigation.ts
import { msg } from 'gt-react';
export const mainNav = [
{
label: msg('Home'),
href: '/',
icon: 'home'
},
{
label: msg('Products'),
href: '/products',
icon: 'package'
},
{
label: msg('About Us'),
href: '/about',
icon: 'info'
}
];
export const footerLinks = [
{
title: msg('Company'),
links: [
{ label: msg('About'), href: '/about' },
{ label: msg('Careers'), href: '/careers' },
{ label: msg('Contact'), href: '/contact' }
]
},
{
title: msg('Support'),
links: [
{ label: msg('Help Center'), href: '/help' },
{ label: msg('Documentation'), href: '/docs' },
{ label: msg('API Reference'), href: '/api' }
]
}
];
```
```tsx
// components/Navigation.tsx
import { useMessages } from 'gt-react';
import { mainNav } from '../config/navigation';
function Navigation() {
const m = useMessages();
return (
);
}
```
### フォームの設定
```tsx
// config/forms.ts
import { msg } from 'gt-react';
export const formMessages = {
placeholders: {
email: msg('Enter your email address'),
password: msg('Enter your password'),
message: msg('Type your message here...')
},
actions: {
send: msg('Send Message'),
save: msg('Save Changes'),
cancel: msg('Cancel')
},
validation: {
required: msg('This field is required'),
email: msg('Please enter a valid email address'),
minLength: msg('Must be at least {min} characters', { min: 8 }),
maxLength: msg('Cannot exceed {max} characters', { max: 100 })
},
success: {
saved: msg('Changes saved successfully'),
sent: msg('Message sent successfully'),
updated: msg('Profile updated')
},
errors: {
network: msg('Network error - please try again'),
server: msg('Server error - please contact support'),
timeout: msg('Request timed out - please try again')
}
};
```
```tsx
// components/ContactForm.tsx
import { useMessages } from 'gt-react';
import { formMessages } from '../config/forms';
function ContactForm() {
const m = useMessages();
const [errors, setErrors] = useState({});
return (
);
}
```
### 動的コンテンツの生成
```tsx
// utils/productData.ts
import { msg } from 'gt-react';
function mockProducts() {
return [
{ name: 'iPhone 15', company: 'Apple', category: 'Electronics' },
{ name: 'Galaxy S24', company: 'Samsung', category: 'Electronics' }
];
}
export function getProductData() {
const products = mockProducts();
return products.map(product => ({
...product,
description: msg('{name} is a {category} product by {company}', {
name: product.name,
category: product.category,
company: product.company
})
}));
}
```
```tsx
// components/ProductList.tsx
import { useMessages } from 'gt-react';
import { getProductData } from '../utils/productData';
function ProductList() {
const m = useMessages();
const products = getProductData();
return (
{products.map(product => (
{product.name}
{m(product.description)}
))}
);
}
```
## よくある問題
### エンコード済みの文字列を直接使用する
[`msg`](/docs/react/api/strings/msg) の出力を直接使用しないでください。
```tsx
// ❌ 誤り - エンコードされた文字列を直接使用
const encoded = msg('Hello, world!');
return {encoded}
; // エンコードされた文字列が表示され、翻訳は表示されない
// ✅ 正しい - 先に文字列をデコードする
const encoded = msg('Hello, world!');
const m = useMessages();
return {m(encoded)}
; // 正しく翻訳された文字列が表示される
```
### msg() 内の動的なコンテンツ
文字列はビルド時に確定している必要があります:
```tsx
// ❌ 誤り - 動的テンプレートリテラル
const name = 'John';
const message = msg(`Hello, ${name}`); // ビルド時エラー
// ✅ 正しい - 変数を使用する
const name = 'John';
const message = msg('Hello, {name}', { name });
```
### デコードし忘れた場合
すべての[`msg`](/docs/react/api/strings/msg)文字列はデコードが必要です。
```tsx
// ❌ デコードが抜けている
const config = {
title: msg('Dashboard'),
subtitle: msg('Welcome back')
};
// コンポーネント内で後から使用 - デコードを忘れた
return {config.title}
; // エンコードされた文字列が表示される
// ✅ 正しい方法 - 使用時にデコードする
const m = useMessages();
return {m(config.title)}
; // 翻訳されたタイトルが表示される
```
## 次のステップ
* [辞書ガイド](/docs/react/guides/dictionaries) - 構造化データで翻訳を整理する
* [言語ガイド](/docs/react/guides/languages) - 対応言語を設定する
* API リファレンス:
* [`msg` 関数](/docs/react/api/strings/msg)