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?