Abhilasha
Abhilasha

Reputation: 141

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.

Upvotes: 13

Views: 15628

Answers (2)

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.

Upvotes: 9

Piyush Dubey
Piyush Dubey

Reputation: 99

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;

Upvotes: 3

Related Questions