Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"i18next backendConnector: loading namespace failed" when using react-i18next useTranslationHooks

I'm trying to implement react-i18next on my create-react-app application with useTranslation() hooks.

However, in the console, the debug mode shows

i18next::backendConnector: loading namespace billingAddress for language en failed failed parsing /locales/en/billingAddress.json to json

and

i18next::translator: missingKey en billingAddress Form.email Customer Email (Default)

i18next.ts

import {initReactI18next} from "react-i18next";
import i18next from "i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-xhr-backend';
import XHR from "i18next-xhr-backend";

i18next
// .use(Backend)
    .use(LanguageDetector)
    .use(XHR)
    .use(initReactI18next) // passes i18n down to react-i18next
    .init({
        lng: "en",
        fallbackLng: {
            'en-US':['en'],
            'zh-CN':['cn'],
            default:['en']
        },
        debug: true,
        ns: ['billingAddress'],
        defaultNS: 'billingAddress',
        // load: "currentOnly",
        interpolation: {
            escapeValue: false // react already safes from xss
        },
        keySeparator: false,
        // backend: {
        //     loadPath: "/locales/{{lng}}/{{ns}}.json",
        //     crossDomain: true
        // },
        react: {
            wait: true,
        }
    });

export default i18next;

files

├── src
│   ├── i18next.ts
│   ├── locales
│   │   ├── cn
│   │   │   └── billingAddress.ts
│   │   └── en
│   │       └── billingAddress.ts
│   ├── index.tsx

version

"react": "^16.8.4",

"i18next": "^15.0.7",

my translation file

export default{
  "Form": {
    "emailLabel": "customer Email",
    "emailPlaceholder": "[email protected]",
  }
}

my billingAddress file

  const [t, i18n] = useTranslation();

    const changeLanguage = (language: string) => (e: React.MouseEvent) => {
        i18n.changeLanguage(language)
    };

const someValues: billingAddress = {
emailLabel: t("Form.emailLabel","Customer Email")
}

return (
<div>
 <button onClick={changeLanguage("en")}>English</button>
<OtherComponent value={someValues} />
</div>
)

I'm quite confuse how to load namespace now... any ideas?

Thanks in advance!

like image 311
WhyINeedToKnowThis Avatar asked Mar 26 '19 05:03

WhyINeedToKnowThis


1 Answers

You might just follow the sample here: https://github.com/i18next/react-i18next/tree/master/example/react/public/locales

Using xhr backend you need to provide valid JSON files as source - that's all.

like image 55
jamuhl Avatar answered Nov 02 '22 07:11

jamuhl