I have a requirement to implement translations for a react js project.
In my project src/locale/i18n.js file
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';
i18n
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(Backend)
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
fallbackLng: 'en',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
});
export default i18n;
And I import this file to index.js
import './locales/i18n'
ReactDOM.render(
<React.StrictMode>
<Suspense fallback="Loading...">
<App />
</Suspense>
</React.StrictMode>,
document.getElementById('root')
);
And in my app.js
import { useTranslation, Trans } from 'react-i18next';
function App() {
const { t, i18n } = useTranslation();
const changeLanguage = (lang) => {
i18n.changeLanguage(lang)
}
return (
<div className="App">
{t('description.part2')}
<button onClick={() => changeLanguage('en')}>EN</button>
<button onClick={() => changeLanguage('si')}>SI</button>
</div>
);
}
also, my translation keys placed in public/locales/en/transalation.json and public/locales/si/transalation.json
This setup works perfectly fine. But I need to load my translations from a backend API. It has a few JSON files and this is the URL format
BASEURL/locales/Language/NameSpace.json
It has few NameSpaces such as
Reports
Common
Dashboard
So If run English translation for common NameSpace,
BASEURL/locales/Language/NameSpace.json
The server returns a JSON object like this
{
"com:search":"search",
"com:logout":"logout"
}
How do I call these API endpoints one time and feed this to the i18n instance? So then I can use these translation keys anywhere in the project like this
<h2>{t("common:com-description")}</h2>
I guess it is better, if you write script for downloading translation into folder public/locales/si/transalation.json
update-i18n.js
const UpdateTranslation = async()=> {
// get translation from backend
const data = await fetch('url')
if (!fs.existsSync(`./public/locales`)) fs.mkdirSync(`./public/locales`);
[data].forEach((lang) => {
if (!fs.existsSync(`./public/locales/${lang}`))
fs.mkdirSync(`./public/locales/${lang}`);
fs.writeFile(
`./public/locales/${lang}/common.json`,
JSON.stringify(result[lang], null, 2),
function (err) {
if (err) return console.log('Error: ', err);
console.log(`/public/locales/${lang}/common.json - updated`);
}
);
}
})