Skip to main content

react-intl गाइड: React अंतरराष्ट्रीयकरण सेटअप

अपने React ऐप में IntlProvider, FormattedMessage, useIntl, ICU message format और ऑटोमेटेड अनुवादों के साथ FormatJS react-intl सेट अप करें।

इसके बजाय react-i18next का उपयोग कर रहे हैं? हमारी react-i18next गाइड देखें

1

react-intl इंस्टॉल करें

react-intl, FormatJS प्रोजेक्ट का हिस्सा है। यह ICU MessageFormat मानक का उपयोग करके स्ट्रिंग, संख्याओं, तारीखों और बहुवचन को फ़ॉर्मैट करने के लिए React कंपोनेंट और हुक उपलब्ध कराता है।

React के अलावा react-intl की कोई runtime dependency नहीं है। यह संख्याओं और तारीखों को फ़ॉर्मैट करने के लिए ब्राउज़र की बिल्ट-इन Intl API का उपयोग करता है और plurals, select तथा rich text के लिए अपना ICU MessageFormat parser उपलब्ध कराता है।
Terminal
npm install react-intl
2

IntlProvider कॉन्फ़िगर करें

अपने ऐप के root पर उसे IntlProvider में रैप करें। सक्रिय locale और flat messages object पास करें। इसके बाद उसके नीचे मौजूद हर कंपोनेंट FormattedMessage या useIntl के ज़रिए अनुवादों को एक्सेस कर सकता है।

src/main.tsx
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>
);
IntlProvider के लिए flat key-value messages object आवश्यक है (उदाहरण के लिए, { "app.greeting": "Hello" })। IntlProvider को पास करने से पहले nested JSON को flat करना होगा या nested structures को बदलने के लिए flat जैसी utility का उपयोग करें।

मैसेज फ़ाइलें

हर locale के लिए एक JSON फ़ाइल बनाएँ। react-intl मूल रूप से ICU MessageFormat syntax का उपयोग करता है—plurals, select और variables, सभी को message strings में inline लिखा जाता है।

messages/en.json & messages/de.json
// 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"
}
व्यवस्थित रखने के लिए "nav.home" जैसे dot-separated IDs का उपयोग करें। react-i18next के विपरीत, react-intl एक flat messages object की अपेक्षा करता है—आप structure को नहीं, keys को flat करते हैं।
3

कंपोनेंट में अनुवादों का उपयोग करें

react-intl आपको दो प्रमुख APIs देता है: अनुवादित JSX रेंडर करने के लिए FormattedMessage component और imperative access (placeholders, aria labels और programmatic formatting) के लिए useIntl hook।

FormattedMessage कंपोनेंट

JSX में declarative translations के लिए FormattedMessage का उपयोग करें। message ID और कोई भी interpolation values पास करें। यह अनुवादित स्ट्रिंग को सीधे रेंडर करता है।

Greeting.tsx
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>
  );
}

useIntl हुक

जब आपको अनुवादित स्ट्रिंग plain value के रूप में चाहिए—जैसे input placeholders, aria-labels, document.title या non-React APIs को स्ट्रिंग पास करते समय—तो useIntl() का उपयोग करें। यह formatNumber, formatDate और formatRelativeTime भी उपलब्ध कराता है।

SearchBar.tsx
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)

अपनी message strings में XML जैसे tags का उपयोग करके अनुवादों के भीतर JSX एम्बेड करें। अनुवादित मैसेज में links, bold text या कोई भी React component रेंडर करने के लिए values prop के ज़रिए tag handlers पास करें।

SignUp.tsx
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>,
      }}
    />
  );
}
FormattedMessage डिफ़ॉल्ट रूप से React Fragment रेंडर करता है। यदि आपको किसी विशेष wrapper element की आवश्यकता है, तो IntlProvider को textComponent prop पास करें या FormattedMessage को अपने element में रैप करें।

@formatjs/cli के साथ मैसेज एक्सट्रैक्शन

FormatJS आपके source code से message IDs को अपने-आप JSON फ़ाइल में एक्सट्रैक्ट करने के लिए CLI उपलब्ध कराता है। इससे manual bookkeeping के बिना आपकी messages file आपके components के साथ sync में रहती है।

Terminal
# 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.json
4

Plurals और ICU Select

react-intl मूल रूप से ICU MessageFormat का उपयोग करता है। Plurals, gender-based select और nested formatting, सभी को सीधे message strings में लिखा जाता है—suffix conventions या अलग keys की आवश्यकता नहीं होती।

ICU plural syntax by language
// 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}個の商品があります"
}
JavaScript में plural logic को कभी hardcode न करें। अरबी जैसी भाषाओं में 6 plural forms होते हैं, फ़्रेंच में 0 को singular माना जाता है और जापानी में singular-plural का भेद नहीं होता। नियमों को ICU MessageFormat पर छोड़ दें—सिर्फ़ count value पास करें।

Gender और Roles के लिए ICU Select

gender, user roles या status values जैसे संदर्भ पर निर्भर अनुवादों के लिए ICU select syntax का उपयोग करें। select expression दी गई value के आधार पर सही variant चुनता है।

ICU select syntax
// 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 }}
/>

अनुवाद की गुणवत्ता जाँचने की प्रक्रिया ऑटोमेट करें

i18n-validate की मदद से गुम keys और टूटे placeholders को रिलीज़ होने से पहले पकड़ें। वास्तविक अनुवाद आने से पहले i18n-pseudo का उपयोग करके pseudo-translations के साथ अपने UI को टेस्ट करें।

आम समस्याएँ

defaultMessage पर बहुत अधिक निर्भरता

defaultMessage development fallback है, अनुवाद की रणनीति नहीं। यदि आप सभी strings के लिए defaultMessage का उपयोग करते हैं, तो आपके message extraction output में अंग्रेज़ी text होगा, लेकिन अनुवादक नई keys से चूक सकते हैं। हमेशा एक संपूर्ण source locale file एक्सट्रैक्ट करके उसका रखरखाव करें।

Flat Keys के बजाय Nested Objects

IntlProvider messages के लिए flat Record&lt;string, string&gt; की अपेक्षा करता है। यदि आप { nav: { home: "Home" } } जैसा nested JSON पास करते हैं, तो react-intl को "nav.home" key नहीं मिलेगी। messages को पास करने से पहले उन्हें flat करें या flat जैसी library का उपयोग करें।

IntlProvider के कारण बार-बार रेंडर होना

यदि आप messages object को render function के भीतर inline बनाते हैं, तो IntlProvider को हर render पर नया object reference मिलता है, जिससे सभी consumers फिर से render होते हैं। useMemo की मदद से messages को memoize करें या उन्हें component के बाहर परिभाषित करें।

Tests में IntlProvider का न होना

यदि FormattedMessage या useIntl का उपयोग करने वाले components को IntlProvider ancestor के बिना render किया जाए, तो वे error throw करेंगे। Tests में अपने component को locale="en" और empty या minimal messages object के साथ IntlProvider में रैप करें।

सुझाया गया फ़ाइल स्ट्रक्चर

Project 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.json

i18n Agent अभी आज़माएँ

अपनी अनुवाद फ़ाइल यहाँ छोड़ें

JSON, YAML, PO, XML, CSV, Markdown, Properties

या ब्राउज़ करने के लिए क्लिक करें

लक्षित भाषाएँ

साइन अप की ज़रूरत नहींतुरंत अनुमान

react-intl-locale-chain के साथ Locale Fallback

जब pt-BR जैसे regional locale में कोई translation key गुम होती है, तो react-intl पहले parent locale pt को जाँचने के बजाय सीधे default locale पर चला जाता है।

Terminal
npm install react-intl-locale-chain
Configuration
<LocaleChainProvider
  fallbacks={{
    'pt-BR': ['pt', 'en'],
    'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
  }}
  defaultLocale="en"
>
  <App />
</LocaleChainProvider>

समर्थित frameworks और 75 built-in chains की पूरी सूची के लिए हमारी Locale Fallback गाइड देखें। Learn more →

अक्सर पूछे जाने वाले सवाल