On using internationalization in React application, Need to load the language translation files on demand using api calls and not have them defined upfront. How can this be achieved by using React-i18next?
Tried out the normal translations being picked from static predefined files using React-i18next. Tried using xhr-backend but unable to find any sample to implement this requirement of on-demand load of translation related data.
this data I am not storing in file but directly using. http://localhost:8080//file_download/en Below is the code import i18next from 'i18next'; import Backend from 'i18next-http-backend'; const LanguageDetector = require('i18next-browser-languagedetector'); const initReactI18next = require('react-i18next'); i18next .
Based on the React i18n framework, react-i18next is another popular internationalization library which uses components to render or re-render the translated content of your application once users request a change of language.
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import backend from 'i18next-http-backend';
import axiosInstance from './helpers/Axios';
const loadResources=async(locale:string)=> {
return await axiosInstance().get('/translate-data/get', { params: { lang: locale } })
.then((response) => { return response.data })
.catch((error) => { console.log(error); });
}
const backendOptions = {
loadPath: '{{lng}}|{{ns}}',
request: (options:any, url:any, payload:any, callback:any) => {
try {
const [lng] = url.split('|');
loadResources(lng).then((response) => {
callback(null, {
data: response,
status: 200,
});
});
} catch (e) {
console.error(e);
callback(null, {
status: 500,
});
}
},
};
i18n
.use(LanguageDetector)
.use(backend)
.init({
backend: backendOptions,
fallbackLng: "en",
debug: false,
load:"languageOnly",
ns: ["translations"],
defaultNS: "translations",
keySeparator: false,
interpolation: {
escapeValue: false,
formatSeparator: ","
},
react: {
wait: true
}
});
export default i18n;
Request from backend options is used to call backend API using Axios.
import i18next from 'i18next';
import XHR from 'i18next-xhr-backend';
var language = i18next.language ||'en-US';
const backendOptions = {
type: 'backend',
crossDomain: false,
allowMultiLoading: false,
loadPath: `your-backend-api/?locale_code=${language}`
}
const options = {
interpolation: {
escapeValue: false, // not needed for react!!
},
initImmediate: false ,
debug: true,
lng: language,
fallbackLng: language,
// have a common namespace used around the full app
ns: ['translations'],
defaultNS: 'translations',
react: {
wait: false,
bindI18n: 'languageChanged loaded',
bindStore: 'added removed',
nsMode: 'default',
defaultTransParent: 'div',
},
};
options['backend'] = backendOptions;
i18next
.use(XHR)
.init(options)
export default i18next;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With