Skip to content

Instantly share code, notes, and snippets.

@Mood-al
Created May 23, 2022 07:34
Show Gist options
  • Save Mood-al/170fc6b7e2f44d5bdfebb1dc95f67c29 to your computer and use it in GitHub Desktop.
Save Mood-al/170fc6b7e2f44d5bdfebb1dc95f67c29 to your computer and use it in GitHub Desktop.
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// this package will help us to get the translations from our API
import Backend from "i18next-http-backend";
// this package will help us to detect the default language of the client browser and set the i18n language to it
import LanguageDetector from "i18next-browser-languagedetector";
import axios from "axios";
import { TRANSLATIONS_BASE_URL } from "./config";
// i18next-http-backend options object that will be passed inside i18next
const backendOptions = {
// your api url
loadPath: TRANSLATIONS_BASE_URL,
// here we will send our request to the api to get the translations
request: async (options, url, payload, callback) => {
// the url prop is passed from loadPath
try {
// make the API call using axios
const translation = await axios.get(url);
// the data shape is like so {"ar" : {"home" : "الرئيسية"} , "en": {"home" : "home}"}
// we got the selected language by using the stored item inside localstorage
// so when we select arabic for instance there will be a string stored inside localstorage named i18nextLng with the value ar
const data = translation.data[localStorage.getItem("i18nextLng")];
callback(null, {
status: 200,
data: JSON.stringify(data),
});
} catch (e) {
callback(null, e);
}
},
};
i18n
// use the backend package so we can be able to make our api call
.use(Backend)
// detect user language
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
.init({
nsSeparator: false,
keySeparator: false,
fallbackLng: false,
debug: true,
// pass the backend option here
backend: backendOptions,
supportedLngs: ["en", "ar"],
});
export default i18n;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment