Reputation: 446
I am new to react-i18nnext library. I try to separate my translations into files so that each page has a separate JSON-file and not one single.
I am confused about how to do the following step from this guide:
I am using the following code to call default translate.json
file:
<h1>{t('title')}</h1>
But I want to call a different file, so I have to use according to the guide:
<h1>{t('test:title')}</h1>
if I use file translation.json
- everything works, but if I am using another name of the file - it fails with error:
i18next::translator: missingKey en test title title
I followed the "Step by Step" guide on the official page of the library.
Here's my i18n.js
file:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// not like to use this?
// have a look at the Quick start guide
// for passing in lng and translations on init
const languages = ['en', 'de', 'et'];
i18n
/*
load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
learn more: https://github.com/i18next/i18next-http-backend
*/
.use(Backend)
/*
detect user language
learn more: https://github.com/i18next/i18next-browser-languageDetector
*/
.use(LanguageDetector)
/*
pass the i18n instance to react-i18next.
*/
.use(initReactI18next)
/*
init i18next
for all options read: https://www.i18next.com/overview/configuration-options
*/
.init({
lng:"ee",
fallbackLng: 'et', // use et if detected lng is not available
saveMissing: true, // send not translated keys to endpoint
debug: true,
whitelist: languages,
// backend: {
// // for all available options read the backend's repository readme file
// loadPath: '/locales/{{lng}}/{{ns}}.json'
// },
react: {
useSuspense: false
}
})
export default i18n;
For a better overview, I added my code to codesandbox:
Upvotes: 6
Views: 17012
Reputation: 35503
In order to use multiple namespaces in the same page, you need to specify it when calling useTranslation
.
export default function App() {
const [t] = useTranslation(["translation", "customFile"]);
// ---------------------------------------------^
return (
<div className="App">
<button onClick={() => changeLanguageOnClick("en")}>English</button>
<button onClick={() => changeLanguageOnClick("de")}>German</button>
<h1>{t("title")}</h1>
<h2>{t("customFile:title")}</h2>
</div>
);
}
This is how it look like: https://codesandbox.io/s/intelligent-shockley-q588u?file=/src/App.js:243-304
Upvotes: 9