Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we load translations using api calls instead of having them defined in static jsons? How can this be done in React-i18next?

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.

like image 592
Abhilasha Avatar asked Jun 25 '19 07:06

Abhilasha


People also ask

How do I incorporate API data in i18next instead of static file?

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 .

What is i18next in React?

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.


2 Answers

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.

like image 113
sruthypriya santhakumar Avatar answered Sep 21 '22 17:09

sruthypriya santhakumar


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;
like image 21
Piyush Dubey Avatar answered Sep 24 '22 17:09

Piyush Dubey