0
votes

I am building a react application with react-i18next as my internationalization library choice. Though I am able to divide my translations file into multiple files and use them in my application, I am concerned that over time these translations could grow and loading them on built is an inefficient approach. It says in their documentation that you can load translations file manually but they do not guide you effectively on how to do so.

At the moment my code is:

18n.js

import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";

import { commonEN, landingEN } from "./locales/en";
import { commonJP, landingJP } from "./locales/jp";


const resources = {
  en: {
    common: commonEN,
    landing: landingEN,
  },
  jp: {
    common: commonJP,
    landing: landingJP
  }
};

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    fallbackLng: "en",
    debug: true,
    ns: ["common"],
    defaultNS: "common",
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

Component.js

import React from 'react'
import "./App.css";
import { Suspense } from "react";
import { useTranslation } from "react-i18next";

function Component() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t("Account")}</h1>
      <h2>{t("landing:title")}</h2>
    </div>
  );
}

export default Component;

common.json

{
    "Account": "Account Name"
}

landing.json

{
    "title": "Landing Page",
    "Privacy": "Privacy and Personalization"
}

I want to load my translations file on component render instead of on application build, how can I do so? What is the best practice involved when handling translation language on the front-end? Is it more effective to load languages from the backend and if so how to load languages on runtime?

2

2 Answers

0
votes

Use the ns parameter to tell i18next which namespaces to load by default when your app loads. If you want to load different namespaces during runtime, the docs say you can call i18next.loadNamespaces('anotherNamespace', (err, t) => { /* ... */ });.

If you're worried about huge JSON files and scalability, you might want to checkout i18nexus.com for managing translations. Super cool platform for managing i18next translation files, and you can even automate with Google Translate.

0
votes

Try the way this vid shows.. Localise React Applications Using I18Next

I was also trying with the approach you posted in question. Did not seem a good choice. So switched to use i18next 'backend'. Just keep files in public folder and they will be fetched when needed.