In this article, you will learn how to configure i18next to server-side translations using i18next-http-backend
library. Additionally, I will show you how to create translation keys automatically with default translation in SimpleLocalize translation editor.
Install dependencies
# Using NPM
npm install --save react-i18next i18next i18next-http-backend i18next-browser-languagedetector axios
# Using yarn
yarn add react-i18next i18next i18next-http-backend i18next-browser-languagedetector axios
Configure i18next
Create i18n.ts
file with i18next-http-backend configuration. i18next-http-backend is responsible for fetching translations from a remote server and for creating new keys used in your project.
import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'
import axios from "axios";
const fallbackLanguage = 'en'
const projectToken = ""; // YOUR PROJECT TOKEN
const apiKey = ""; // YOUR API KEY
const loadPath = `https://cdn.simplelocalize.io/${projectToken}/_latest/{{lng}}`;
const addMissingTranslationsEndpoint = `https://api.simplelocalize.io/api/v1/translations`;
i18n
.use(Backend)
.use(LanguageDetector)
.use (initReactI18next)
.init({
fallbackLng: fallbackLanguage,
backend: {
loadPath: loadPath
},
saveMissing: true,
missingKeyHandler: (lngs, ns, key, fallbackValue) => {
const configuration = {
headers: {
'X-SimpleLocalize-Token': apiKey
}
};
const requestBody = {
content: [
{
key: key,
language: fallbackLanguage,
text: fallbackValue
}
]
}
axios.post(addMissingTranslationsEndpoint, requestBody, configuration)
}
})
export default i18n;
Configure i18next in application
Import i18n.ts
file in index.ts
by adding import './i18n';
Whole index.ts
file should look like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import './i18n'; // import i18next configuration (!!)
ReactDOM.render (
<React.StrictMode>
<Suspense fallback={<div>Loading...</div>}>
<App />
</Suspense>
</React.StrictMode>,
document.getElementById('root')
);
Example usage
import React from "react";
import { useTranslation } from "react-i18next";
function App() {
const { t, i18n } = useTranslation();
return (
<div>
<p>
{t("USE_BUTTONS_BELOW")}
</p>
<button onClick={() => i18n.changeLanguage("en")}>English</button>
<button onClick={() => i18n.changeLanguage("es")}>Spanish</button>
</div>
);
}
export default App;
Use t
function to get translation from given translation key
t("USE_BUTTONS_BELOW")
Switch languages with i18n.changeLanguage(language)
. i18n
object comes from React Hook called useTranslations()
;
Translate and publish changes
Now, your users will see the updated translation every time you click 'Publish' button in the translation editor!
More resources: