How to change language locally in react-i18next?

Viewed 487

I'm trying to give user an option to specify language of generated receipt while keeping the language of the app the same. How would I change the language only for receipt component? i18n.changeLanguage does it globally.

If it helps, here is my i18n config:

i18n
.use(Backend)
.use(initReactI18next)
.init({
    ns: ["translation", "login", "orders", "products", "invoices"],
    defaultNS: "translation",
    lng: "sl",
    fallbackLng: "en",
    debug: process.env.NODE_ENV === "development",
    interpolation: {
        escapeValue: false,
    },
    react: {
        useSuspense: true,
        wait: true,
    },
});
1 Answers

You can use the getFixedT method to get translations of a particular object in a given language regardless of the global language. Here is an example:

en.json

{
 nested: {
  object: {
   ...
  }
 }
}

App.jsx

import { getFixedT } from "i18next";

const App = () => {
  const fixedT = getFixedT("en");
  const templateData = fixedT("nested.object", {
      returnObjects: true,
    });
}

References

i18next official documentation: getFixedT

Related