Localization Conventions

Proper localization ensures that your application is accessible to a global audience by supporting multiple languages. To implement localization in your ReactJS project, we use i18next along with its React integration, react-i18next.

Configuration

Localization is configured in i18n.ts, where we import language resource files and initialize i18next with these resources. We also use the i18next-browser-languagedetector to detect the user’s language.
// i18n.ts
import i18n from "i18next";
// ... other imports ...

const resources = {
  de: {
    translation: TRANSLATION_DE,
  },
  en: {
    translation: TRANSLATION_EN,
  },
};

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    fallbackLng: "de",
    debug: true,
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

Translation Files

Organize your translations into separate JSON files for each language, like i18n/de/translation.json and i18n/en/translation.json. Group your translations by namespaces or functional areas to maintain clarity and manageability.
// i18n/de/translation.json
{
  "auth": {
    "noAccount": "Kein Account? Melde dich kostenlos an.",
    // ... other translations ...
  },
  // ... other namespaces ...
};

Usage in Components

To use translations in your components, import the useTranslation hook from react-i18next and access the t function to retrieve the translated strings.
import { useTranslation } from "react-i18next";

const MyComponent = () => {
  const { t } = useTranslation();

  return (
    <div>
      <p>{t("auth.email")}</p>
    </div>
  );
};

Best Practices

  • Avoid Hardcoded Strings: Ensure that all strings displayed to the user are translated. Avoid using hardcoded strings to facilitate easier localization into different languages.
  • Structured Translation Files: Maintain structured and organized translation files. Group related translations together for better manageability.
  • Namespace Usage: Use namespaces in your translation files to categorize translations and avoid conflicts.
By following these conventions, you ensure that your application is ready for a global audience, with the flexibility to support multiple languages and adapt to various locales.