Detailed Guide to React Internationalization

React Internationalization

Internationalization enables developers to create applications that adapt to different languages and cultural preferences without modifying the core code. This approach helps businesses deliver a personalized, accessible experience to users worldwide. 

For companies planning to expand globally, partnering with an experienced React development company can make this process much smoother. Modern React libraries like react-intl simplify translation management and provide efficient support for multiple locales. Instead of creating separate app versions for each language, React internationalization lets you maintain a single codebase while delivering localized experiences and supporting multiple languages efficiently.

This blog discusses React internationalization, its importance, available libraries, and the procedure for implementing it. It also distinguishes between internationalization and localization, and provides implementation best practices to keep in mind.

1. What is React Internationalization?

React internationalization, or i18n, refers to adding support for multiple languages and locale-specific conventions to React applications. This includes handling different time zones, text directions, currencies, date and number formats, and other locale-dependent features. The goal is to ensure that applications—whether desktop, web, or mobile- adapt correctly to users’ languages and regional settings across operating systems. 

2. Why Do We Need Internationalization?

Let’s discuss some significant reasons to understand the necessity for internationalization of applications:

  • Increase Global Reach: Making the application accessible in multiple languages enables businesses to build a global presence and expand growth potential.
  • Improve user experience: Allowing users to interact with the applications in their native languages simplifies use. Supporting flexible layouts (for example, right-to-left text direction), adapting date and number formats, and ensuring cultural sensitivity improves usability for diverse audiences. 
  • Boosts Accessibility and Inclusion: Accounting for cultural, linguistic, and physical requirements increases inclusivity and better serves users from varied backgrounds, including people who rely on assistive technologies. 
  • Reduces Future Engineering Efforts: Integrating i18n at the start of development eliminates extensive refactoring or rewrites later to add languages and regions, saving time and increasing efficiency. 
  • Complies with Legal and Regional Requirements: Countries may have their own rules for language mandates, industry standards, privacy protection, accessibility standards, etc. Internationalization helps comply with such localization laws.
  • Supports Business Scalability: With i18n addition of a new locale is just the creation of a new resource file, thus minimizing rework and enabling faster time to market.
  • Enhances Multilingual SEO: With proper SEO internationalization, such as adding appropriate URL structures and hreflang tags, the possibility of your application coming up in the local search results increases, resulting in higher organic traffic and conversion rates.

3. Libraries Used For React Internationalization (i18n)

The internalization libraries in the React ecosystem have evolved repeatedly to meet the evolving needs of applications and to keep pace with market trends. Early libraries were basic, offered limited support for translations, and required substantial manual effort. 

Let’s discuss the popular React internationalization libraries that you can use to integrate internationalization into your React applications:

Library NameDescriptionFeatures
react-i18nextA React localization library (approximately 15 KB bundle) built on top of the i18next framework.
  • Lightweight
  • Plugins and integrations
  • Built-in language detector
  • Supports both CSR and SSR
  • Lazy loading
  • Dynamic translation
  • Higher-order component (HOC) and hooks for language handling
React Intlreact-intl extends FormatJS and relies on JavaScript’s native Intl API. It follows ECMA-402 standards and provides React components and APIs to format dates, numbers, plurals, and strings.
  • Mimics ICU MessageFormat syntax for advanced formatting
  • Strong TypeScript support
  • React context and hooks support
  • Large, active community
  • Supports more than 150 languages
React-intl-universalBuilt by Alibaba Group on top of react-intl. It enables internalization outside React components as well, so it can be used in plain JavaScript (Vanilla JS) code.
  • Lightweight
  • Supports over 150 languages
  • Requires minimal setup
  • Simple API for translations
  • Variables in messages
  • Runs in browser and Node.js
  • Comparatively smaller community
LinguiJSA JavaScript internationalization library well-suited for performance-focused projects.
  • CLI workflow management with Lingui tools
  • Supports Unicode ICU MessageFormat standards
  • Supports code-splitting and message catalogs
  • Automatic message extraction and compile-time validation
  • Integrations for machine translations
  • Minimal configuration with macro-based syntax
Polyglot.jsA lightweight JavaScript internationalization helper library.
  • Simple phrase interpolation
  • No external dependencies
  • Runs in browser and CommonJS environments (Node.js)

4. Implementation Using I18Next

Before you begin, initialize your project using Create React App. Below is a step-by-step procedure to implement internationalization in a React application for users from different regions and languages:

Step 1: Install Required Packages

First, install i18next and its React bindings, plus optional plugins for language detection and backend support. The backend library lets you load translations from a remote server or local files. The language detector plugin helps determine the user’s preferred language. Example packages to install.

  • i18next
  • react-i18next
  • i18next-browser-languagedetector (or another detector)
  • i18next-http-backend (or another backend)
npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector
PackageUsed ForExample Use
i18nextCore translation engineTranslation logic, interpolation, plurals
react-i18nextReact integrationuseTranslation(), <Trans>, <I18nextProvider>
i18next-http-backendLoad translations from JSON filesLoad /locales/en/translation.json dynamically
i18next-browser-languagedetectorDetect user language automaticallyUse the browser’s language preference on first load

Step 2: Create i18n Configuration File

We’ll now initialize the React-i18next. Create a new file named i18n.js in your src folder. Create an instance of the i18n object and configure it with the settings below.

import i18n from "i18next"; 
import { initReactI18next } from "react-i18next"; 
import Backend from "i18next-http-backend"; 
import LanguageDetector from "i18next-browser-languagedetector"; 
const supportedLngs = { 
  en: { name: "English", dir: "ltr" }, 
  ar: { name: "العربية", dir: "rtl" }, 
}; 
 
 
i18n 
  .use(Backend) // Load translation files
  .use(LanguageDetector) // Automatically detect user language preference
  .use(initReactI18next) 
  .init({ 
    fallbackLng: "en", // Use English if the detected language is not supported
    supportedLngs: Object.keys(supportedLngs), 
    interpolation: { 
      escapeValue: false, 
    }, 
    backend: { 
      loadPath: "/locales/{{lng}}/translation.json", // Path   to fetch translation files dynamically based on language
    }, 
    detection: { 
      order: ["cookie", "localStorage", "navigator"], // Language detection priority:
    }, 
  }); 
 export default i18n;

Step 3: Import i18n in Your App

Import the i18n configuration into your main index.js or App.js file. This initializes i18n globally for your application.

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import "./i18n";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

Note: Formatting dates, numbers, and currencies according to the user’s locale is an important part of internationalization, and can be achieved using the JavaScript Intl API or libraries like React Intl.

Step 4: Create Translation Files

Translation files must be organized to support adding multiple languages to your application. JSON files are used in the React-i18next library to store translations. Create a separate JSON file for each language your application will support. In this example, create two files: en/translation.json and ar/translation.json for English and Arabic, respectively. 

React i18next implements the concept of namespaces from i18next to facilitate the organization and loading of translations into multiple files. Use a folder structure such as public/locales to store these translation files. Within locales, create subfolders en and ar to hold the respective language files. This structure makes it easy to manage and load translations when needed.

public/  
  locales/  
    en/  
      translation.json  
    ar/  
      translation.json

public/locales/ en/translation.json

{ 
  "welcome": "Welcome", 
  "greeting": "Hello, {{name}}", 
  "description": "This is a sample application with 	   	internationalization" 
}

public/locales/ar/translation.json

{ 
  "welcome": "مرحباً", 
  "greeting": "أهلاً بك، {{name}}", 
  "description": "هذا تطبيق نموذجي مع تدويل" 
}

Step 5: Use Translations in Components

There are several ways to use translations in your components: 

1. Using the useTranslation Hook

We’ll use the useTranslation Hook to access the translation function, t, to translate the content i18n instance to change the language.

import "./App.css"; 
import './i18n'; 
import LanguageSwitcher from "./LanguageSwitcher" 
import { useTranslation } from 'react-i18next';  
function App() { 
  const { t } = useTranslation(); 
  return ( 
    <div> 
      <LanguageSwitcher/> 
      <h1>{t("welcome")}</h1> 
      <p>{t("greeting", { name: "John" })}</p> 
      <p>{t("description")}</p> 
    </div> 
  ); 
} 
export default App;

2. Using the withTranslation HOC 

The classic higher-order component (HOC), withTranslation, uses props to get the t function and i18n instance inside your component.

import { withTranslation } from 'react-i18next';  
function MyComponent({ t }) {  
  return <h1>{t('welcome')}</h1>;  
} 
export default withTranslation()(MyComponent);

3. Using the Trans Component for Complex Translations 

The Trans component allows nesting of components to be translated within one translation key.

import { Trans } from "react-i18next"; 
function MyComponent() { 
  return ( 
    <Trans i18nKey="complexText"> 
      This is a <strong>complex</strong> text with <a href="#">links</a>. 
    </Trans> 
  ); 
} 
export default MyComponent;

State management is important for keeping track of the current language and ensuring the correct translations are displayed throughout the app. Using a centralized state or context can help maintain consistency and improve scalability as your application grows.

Step 6: Add Language Switcher

Create a component that allows users to switch languages manually.

import { useTranslation } from "react-i18next";
function LanguageSwitcher() {
 const { i18n } = useTranslation();
 const currentLanguage = i18n.language;
 const changeLanguage = (lng) => {
   i18n.changeLanguage(lng);
 };
 return (
   <div>
     <button
       onClick={() => changeLanguage("en")}
       variant={currentLanguage === "en" ? "contained" : "outlined"}
     >
       English
     </button>{" "}
     <button
       onClick={() => changeLanguage("ar")}
       variant={currentLanguage === "ar" ? "contained" : "outlined"}
     >
       Arabic
     </button>
   </div>
 );
}
export default LanguageSwitcher;

Language selection is a key part of providing a personalized user experience. You can enhance this by saving the user’s language choice in localStorage, so their preference is remembered across sessions.

Add the following code to your existing i18n.js configuration file.

const updateDocumentDirection = (lng) => {
 const dir = supportedLngs[lng]?.dir || "ltr";
 document.documentElement.dir = dir;
 document.documentElement.lang = lng;
};
updateDocumentDirection(i18n.language);
i18n.on("languageChanged", (lng) => {
 updateDocumentDirection(lng);
});

5. Internationalization vs Localization

Internationalization and localization are related but distinct concepts; developers often confuse them. It is important to understand their differences before starting an internationalization effort.

ParametersInternationalizationLocalization
DefinitionDeveloping multilingual software designed for use across different regions.Adapting an internationalized app to support a specific language/region.
GoalMake the software adaptable for future translations.Provide culturally appropriate content and experiences.
Who performs it?Developers and content creators.Translators, marketwers, project managers, proofreaders, and testers.
When is it performed?During software development.After the software internationalization.
How does it work?Separates linguistic and cultural data from application functionality so content can be adapted without changing core code.Adapts products, services, and content to a specific cultural or linguistic market.
What does it involve?Setting up frameworks, placeholders, and dynamic formats.Text translation, adjusting date/number formats, and changing images or other cultural elements.
Tools Usedi18next, react-intl, LinguiJS, FormatJS.Lokalise, Phrase, Crowdin, and manual translation workflows.
FocusCode architecture and structure to support multiple locales.Content, visuals, and formatting tailored to a specific region.
ActionsPrepare the codebase to receive multiple languages and locale configurations.Translate and adapt content for users in a specific country or region. 
OutcomeA multilingual-ready application.A localized user experience that increases the company’s relevance and influence in the local market.

6. React Internationalization Best Practices

The internationalization libraries will ease your task, but they won’t resolve all coding or translation issues that arise during implementation. The following five best practices will help you address those challenges:

  1. Standardize Code: Keep the code structure consistent throughout the project. Standardize variable naming, formatting, and coding style to ensure uniformity and comparability. A clean, standardized starting point reduces rework and minimizes errors. 
  2. Carefully Reviewing the Language Options: Assess the languages supported by distribution platforms, such as Google Play and the App Store, before planning internationalization. Although React internationalization libraries support many languages, distributing platforms may impose limits. 
  3. Create a Buffer: Text length can expand or contract when translated. Reserve approximately a 30% buffer in UI layouts to accommodate text expansion and contraction. 
  4. Test and Retest: Test the application thoroughly across multiple cycles with both users and developers, and maintain a strong feedback channel to ensure testing reliability. Consider beta testing to evaluate users’ perception of the UI and identify improvements. 
  5. Establish a Continuous Localization Approach: Design a strategy to deliver updates across all supported languages so that localization keeps pace with product changes.

7. Final Thoughts

Internationalizing your React application expands its reach to both regional and global users. It’s a cost-efficient strategy that reduces future expenses by enabling you to target users in different countries. Adding internationalization support is not a one-time task; it requires ongoing collaboration between technical teams and subject-matter experts.

profile-image
Parind Shah

Parind Shah is responsible for frontend innovations at TatvaSoft. He brings profound domain experience and a strategic mindset to deliver exceptional user experience. He is always looking to gain and expand his skill set.

Comments

Leave a message...