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?
Whenever the
i18n
fails to recognize the givenkey
(e.g.,heroTitle
), it would display thekey
instead as a last resort - which is good news as it indicates that thereact-i18next
module is functioning properlyIn your case, the only problem is that you have set the
loadPath
incorrectly, as @Malcolm mentioned. Let's take a closer inspection on yourloadPath
:Using
en
as an example, theloadPath
is set with an absolute path, it implies that it would load the translation files athttp://localhost:8080/locales/en/translation.json
(assuming the port is8080
), instead ofhttp://localhost:8080/public/locales/en/translation.json
.You would want to change the above settings into either two paths:
The above two solutions should help.