Search code examples
javascriptreactjsreact-i18next

Why is react i18next not working ? no errors


The translations do not work I only see the keys. Instead of having "Welcome to MySite" I only have "welcome.title MySite".

my i18nextConf.js file

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

const fallbackLng = ['fr'];
const availableLanguages = ['en','fr'];

i18n
    .use(Backend) // load translations using http (default public/assets/locals/en/translations)
    .use(LanguageDetector) // detect user language
    .use(initReactI18next) // pass the i18n instance to react-i18next.
    .init({
        fallbackLng, // fallback language is english.
        backend: {
            /* translation file path */
            // loadPath: './translations/{{lng}}/{{ns}}.json'
            loadPath: './translations/{{lng}}/common.json'
        },

        detection: {
            checkWhitelist: true, // options for language detection
        },

        debug: false,

        whitelist: availableLanguages,

        interpolation: {
            escapeValue: false, // no need for react. it escapes by default
        },
    });

export default i18n;

My index.js file

import React,{ Suspense } from 'react';
import './i18nextConf';

// code omitted

ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <Suspense fallback={null}>
                <App />
            </Suspense>
        </Provider>
    </React.StrictMode>,
    document.getElementById('root')
);

My translations files in src/translations/en/common.json and src/translations/fr/common.json

{
    "welcome": {
        "title": "Welcome to "
    }
}

my CustomComponent.js

import React,{ Component } from 'react';
import { withTranslation } from "react-i18next";
class CustomComponent extends Component {
    render() {
        const { t } = this.props;

        return (
            <div className="section-title">
                <h2 className={classes.myTitle}>{t('welcome.title')}</h2>
            </div>
        );
    }
}

export default withTranslation()(CustomComponent);

Is there something wrong with my configuration ? What do I have to change ?


Solution

  • Those translation files will be served from the base path from where your index.html is also loaded and in-case it's an app created using create-react-app, that folder is public.

    So I think when you are saying in loadPath that load files from ./translations/{{lng}}/common.json, the request actually gets resolved to public/translation/en/common.json but your files are located at src..... as you stated.

    You can try either moving those files inside public (check this example for reference also ) or you can try the other syntax where you explicitly import the json from each file (inside src) and add it to a resources object which you pass to configuration as shown here