Search code examples
reactjsi18nextreact-i18next

React i18next::backendConnector issue whenever I change the namespace


-hello, I've learned i18n yesterday, everything works fine but I get an issue whenever I change the namespace of the locale file from translation.json to otherNameSpace.json, I always get this message on the browser console:

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

here's my files structure enter image description here

my file i18n.js:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';

i18n.use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        debug: true,
        fallbackLng: "en"
    })

export default i18n;

and here's the file where I used useTranslation hook where I gave the name of my namespace header.js:

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

export const Header = () => {
   const { t, i18n } = useTranslation("header");

   // on change the language
   const changeLanguage = (e) => {
      const newLange = e.currentTarget.value;
      i18n.changeLanguage(newLange)
   }

   return (
      <> 
      <select defaultValue={ localStorage.getItem("i18nextLng") || "en"} 
      className='select_lang' onChange={changeLanguage}>
         <option value="en">En</option>
         <option value="fr">Fr</option>
      </select>
      // I make translation on this button and some other elements
      <button className='btnLoginHeader'>{t("loginBtn")}</button>
      </>
   );
}

can someone tell me what I need to search for or what I need to learn to solve this issue? thanks in advance


Solution

  • By default i18next sets the ns and defaultNS option to 'translation' https://www.i18next.com/overview/configuration-options#languages-namespaces-resources enter image description here

    If you do not have that namespace, set those options to a different value, i.e.:

    import i18n from 'i18next';
    import { initReactI18next } from 'react-i18next';
    import LanguageDetector from 'i18next-browser-languagedetector';
    import Backend from 'i18next-http-backend';
    
    i18n.use(Backend)
        .use(LanguageDetector)
        .use(initReactI18next)
        .init({
            debug: true,
            fallbackLng: "en",
            ns: ["header"],
            defaultNS: "header"
        })
    
    export default i18n;
    

    Additionally, make sure your translations files are valid JSONs.

    btw: If you don't want to manage your translation files manually or are simply looking for a better management solution, take a look at i18next-locize-backend.