i18next package is not working with vite app

506 Views Asked by At

I work on vite/react project and I have installed i18next package to handle translation, but the translation is not appearing instead the key of translation appears instead. Here is mt 18n.js file located in src dir:

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

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',
    },

    lng: localStorage.getItem('i18nextLng') || 'en',
    fallbackLng: 'en',
    whitelist: ['en', 'ar'],

    react: {
      wait: true,
    },
  })

export default i18n

and here is my main.jsx file form wrapping the 18n as provider:

import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter as Router } from 'react-router-dom'
import App from './App.jsx'
import './index.css'
import i18n from './i18n.js'
import { I18nextProvider } from 'react-i18next'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <React.Suspense fallback='loading...'>
    <Router>
    <I18nextProvider i18n={i18n}>
        <App />
    </ I18nextProvider>
    </Router>
    </React.Suspense>
  </React.StrictMode>,
)

I have my translation.json files located in public/locales/en/translation.json

which contains the translation as followins:

{
    "heroTitle": "Welcome to My Website",
    "heroSubTitle": "Find everything you need"
}

and the following is my code in the component that I am working on:

function Hero() {
    const { t } = useTranslation()
  return (
    <div>
        <h1>{t("heroTitle")}</h1>
        <h3>{t("heroSubTitle")}</h3>
    </div>
  )
}

export default Hero

when I run the app the following text appears:

heroTitle
heroSubTitle

how to make the values appear instead?

1

There are 1 best solutions below

0
On

Whenever the i18n fails to recognize the given key (e.g., heroTitle), it would display the key instead as a last resort - which is good news as it indicates that the react-i18next module is functioning properly

In your case, the only problem is that you have set the loadPath incorrectly, as @Malcolm mentioned. Let's take a closer inspection on your loadPath:

loadPath: '/locales/{{lng}}/{{ns}}.json',

Using en as an example, the loadPath is set with an absolute path, it implies that it would load the translation files at http://localhost:8080/locales/en/translation.json (assuming the port is 8080), instead of http://localhost:8080/public/locales/en/translation.json.

You would want to change the above settings into either two paths:

  1. Using absolute path:
loadPath: '/public/locales/{{lng}}/{{ns}}.json',
  1. Using relative path:
loadPath: '../public/locales/{{lng}}/{{ns}}.json',

The above two solutions should help.