
Gabay sa react-intl: Setup ng Internationalization sa React
I-set up ang FormatJS react-intl sa inyong React app gamit ang IntlProvider, FormattedMessage, useIntl, ICU message format, at automated translations.
Gumagamit kayo ng react-i18next sa halip? Tingnan ang aming gabay sa react-i18next
I-install ang react-intl
Bahagi ng FormatJS project ang react-intl. Nagbibigay ito ng mga React component at hook para mag-format ng mga string, number, date, at plural gamit ang pamantayang ICU MessageFormat.
npm install react-intlI-configure ang IntlProvider
I-wrap ang inyong app sa IntlProvider sa root. Ipasa ang aktibong locale at isang flat messages object. Pagkatapos, maa-access ng bawat component sa ibaba ang mga pagsasalin sa pamamagitan ng FormattedMessage o useIntl.
import React from 'react';
import ReactDOM from 'react-dom/client';
import { IntlProvider } from 'react-intl';
import App from './App';
import enMessages from './messages/en.json';
import deMessages from './messages/de.json';
const messages: Record<string, Record<string, string>> = {
en: enMessages,
de: deMessages,
};
// Detect locale from browser or your routing layer
const locale = navigator.language.split('-')[0] || 'en';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<IntlProvider locale={locale} messages={messages[locale] || messages.en}>
<App />
</IntlProvider>
</React.StrictMode>
);Mga Message File
Gumawa ng tig-isang JSON file para sa bawat locale. Native na gumagamit ang react-intl ng ICU MessageFormat syntax—ang plurals, select, at variables ay lahat ipinapahayag inline sa mga string ng message.
// messages/en.json
{
"app.greeting": "Hello, {name}!",
"nav.home": "Home",
"nav.about": "About",
"nav.settings": "Settings",
"cart.itemCount": "{count, plural, one {# item} other {# items}} in your cart"
}
// messages/de.json
{
"app.greeting": "Hallo, {name}!",
"nav.home": "Startseite",
"nav.about": "Über uns",
"nav.settings": "Einstellungen",
"cart.itemCount": "{count, plural, one {# Artikel} other {# Artikel}} in Ihrem Warenkorb"
}Gamitin ang Mga Pagsasalin sa Mga Component
Nagbibigay ang react-intl ng dalawang pangunahing API: ang FormattedMessage component para mag-render ng isinaling JSX, at ang useIntl hook para sa imperative access (placeholder, aria label, programmatic formatting).
Component na FormattedMessage
Gamitin ang FormattedMessage para sa declarative translations sa JSX. Ipasa ang message ID at anumang interpolation value. Ire-render nito nang direkta ang isinaling string.
import { FormattedMessage } from 'react-intl';
function Greeting({ userName }: { userName: string }) {
return (
<div>
<h1>
<FormattedMessage
id="app.greeting"
values={{ name: userName }}
/>
</h1>
<nav>
<a href="/"><FormattedMessage id="nav.home" /></a>
<a href="/about"><FormattedMessage id="nav.about" /></a>
</nav>
</div>
);
}Hook na useIntl
Gamitin ang useIntl() kapag kailangan ninyo ang isinaling string bilang plain value—para sa input placeholder, aria-label, document.title, o kapag nagpapasa ng mga string sa mga non-React API. Nagbibigay din ito ng formatNumber, formatDate, at formatRelativeTime.
import { useIntl } from 'react-intl';
function SearchBar() {
const intl = useIntl();
return (
<input
type="search"
placeholder={intl.formatMessage({ id: 'search.placeholder' })}
aria-label={intl.formatMessage({ id: 'search.ariaLabel' })}
/>
);
}
// useIntl also gives you formatNumber, formatDate, formatRelativeTime:
function PriceTag({ amount, currency }: { amount: number; currency: string }) {
const intl = useIntl();
return (
<span>{intl.formatNumber(amount, { style: 'currency', currency })}</span>
);
}Rich Text (HTML sa Mga Pagsasalin)
Mag-embed ng JSX sa loob ng mga pagsasalin gamit ang XML-like tag sa inyong mga string ng message. Ipasa ang mga tag handler sa pamamagitan ng values prop para mag-render ng link, bold na teksto, o anumang React component sa loob ng isang isinaling message.
import { FormattedMessage } from 'react-intl';
// Message: "By signing up, you agree to our <link>Terms</link>."
// Key: "signup.terms"
// Value: "By signing up, you agree to our <link>Terms</link>."
function SignUp() {
return (
<FormattedMessage
id="signup.terms"
values={{
link: (chunks) => <a href="/terms" className="underline">{chunks}</a>,
}}
/>
);
}Message Extraction gamit ang @formatjs/cli
Nagbibigay ang FormatJS ng CLI para awtomatikong i-extract ang mga message ID mula sa inyong source code papunta sa isang JSON file. Tinitiyak nito na nananatiling naka-sync ang inyong messages file sa mga component nang walang mano-manong bookkeeping.
# Install the CLI
npm install -g @formatjs/cli
# Extract messages from source code into a JSON file
formatjs extract 'src/**/*.tsx' --out-file messages/en.json --id-interpolation-pattern '[sha512:contenthash:base64:6]'
# Or use explicit IDs (recommended):
formatjs extract 'src/**/*.tsx' --out-file messages/en.json
# Compile messages for production (optional, improves perf)
formatjs compile messages/en.json --out-file compiled/en.json
formatjs compile messages/de.json --out-file compiled/de.jsonPlurals at ICU Select
Native na gumagamit ang react-intl ng ICU MessageFormat. Ang plurals, gender-based select, at nested formatting ay lahat ipinapahayag nang direkta sa mga string ng message—walang kailangang suffix convention o hiwalay na key.
// ICU MessageFormat syntax — react-intl uses this natively
// English
{
"cart.itemCount": "{count, plural, one {# item} other {# items}} in your cart",
"inbox.unread": "You have {count, plural, =0 {no unread messages} one {# unread message} other {# unread messages}}"
}
// Arabic — 6 plural forms
{
"cart.itemCount": "{count, plural, zero {لا عناصر} one {عنصر واحد} two {عنصران} few {# عناصر} many {# عنصرًا} other {# عنصر}} في سلتك"
}
// Japanese — 1 form (other)
{
"cart.itemCount": "カートに{count}個の商品があります"
}ICU Select para sa Gender at Mga Role
Gamitin ang ICU select syntax para sa mga pagsasaling nakadepende sa context tulad ng gender, mga role ng user, o mga value ng status. Pinipili ng select expression ang tamang variant batay sa ibinigay na value.
// Gender-dependent messages using ICU select
{
"user.greeting": "{gender, select, male {He} female {She} other {They}} liked your post.",
"user.invitation": "{role, select, admin {You can manage all settings.} editor {You can edit content.} other {You can view content.}}"
}
// Usage:
<FormattedMessage
id="user.greeting"
values={{ gender: user.gender }}
/>I-automate ang Kalidad ng Pagsasalin
Mga Karaniwang Pitfall
Sobrang Pag-asa sa defaultMessage
Mga Nested Object sa Halip na Flat Key
Nagiging Sanhi ang IntlProvider ng Re-render
Walang IntlProvider sa Mga Test
Inirerekomendang File Structure
my-react-app/
├── messages/
│ ├── en.json # Source of truth (English)
│ ├── de.json # German
│ ├── ja.json # Japanese
│ └── es.json # Spanish
├── compiled/ # Optional: compiled messages for prod
│ ├── en.json
│ └── ...
├── src/
│ ├── main.tsx # App entry with IntlProvider
│ ├── App.tsx
│ └── components/
│ ├── Greeting.tsx # Uses FormattedMessage
│ └── SearchBar.tsx # Uses useIntl
└── package.jsonSubukan ang i18n Agent Ngayon
I-drop dito ang inyong translation file
JSON, YAML, PO, XML, CSV, Markdown, Properties
o i-click para mag-browse
Mga target language
Locale Fallback gamit ang react-intl-locale-chain
Kapag nawawala ang translation key sa isang regional locale tulad ng pt-BR, diretso ang react-intl sa default locale sa halip na suriin muna ang parent locale na pt.
npm install react-intl-locale-chain<LocaleChainProvider
fallbacks={{
'pt-BR': ['pt', 'en'],
'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
}}
defaultLocale="en"
>
<App />
</LocaleChainProvider>Tingnan ang aming Locale Fallback Guide para sa kumpletong listahan ng mga sinusuportahang framework at 75 built-in chain. Learn more →