Multi language support - GluedIn
Introduction
This document provides comprehensive steps for integrating localization into your existing or new React application, enabling support for multiple languages.
Enabling Localization in Your App
Follow these key steps to implement localization:
1. Install the Localization Library: Run the following command to install react-i18next:
npm install react-i18next
2. Create translation.js File: Create a translation.js file and add the below code. This file initializes i18next and imports language JSON files to provide translation resources.
import ar from "../languages/ar.json"; // Arabic language file
import en from "../languages/en.json"; // English language file
import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// Translation resources
const resources = {
  en: { translation: en },
  ar: { translation: ar },
};

// Retrieve the default language from localStorage or set it to 'en'
let storedValue = localStorage.getItem("defaultLanguage");
if (!storedValue) {
  localStorage.setItem("defaultLanguage", "en");
  storedValue = "en";
}

// Initialize i18n with React integration
i18n.use(initReactI18next).init({
  resources,
  lng: storedValue,
});

// Set text direction for the document based on the selected language
const targetElement = document.getElementById("direction");
if (targetElement) {
  targetElement.setAttribute("dir", i18n.dir());
}

export default i18n;t
3. Initialize i18n in App.js: Import and initialize i18n in your App.js file as follows:
import React from "react";
import i18n from "./translation/translation"; // Import the i18n configuration

function App() {
  i18n.init(); // Initialize i18n

  // Your app code

  return (
    // Your app components go here
  );
}

export default App;
Additional Notes
  • Language JSON Files: Ensure the language files (ar.json, en.json, etc.) are located in the languages directory and follow the JSON format with key-value pairs.
  • Adding More Languages: To add more languages, import and include them in the resources object in translation.js.
  • Language Switching: Implement a function in your app to change the language and update localStorage accordingly.
Example of a Language JSON File (en.json)
{
  "home": "Home",
  "welcome": "Welcome to the app",
  "logout": "Logout"
}
By following these steps, you will enable multilingual support in your React application, providing an enhanced experience for users who speak different languages.