background
- support multiple languages, need a language switcher in application.
- language changes not associate with routes.
requirements
i18next
react-i18next
i18next-browser-languagedetector
i18next-http-backend
code
i18.ts
i18n
// load translation using http -> see /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({
ns: [
"translation",
"header",
"note",
"settings",
"zod",
"custom",
"introduce",
"message",
],
defaultNS: "translation",
fallbackLng: "en",
debug: false,
detection: {
caches: ["localStorage"],
},
});
export default i18n;
main.ts
import "./i18";
locale files
Put json file in the /public/locales/
, if you add one json to each language, you need to add its filename to 'ns' in config, like above i18.ts
.
[images]
using example
basic useTranslation
import { useTranslation } from "react-i18next";
const { t } = useTranslation();
<button className="btn border truncate" onClick={handleSignIn}>
{t("sign-in")}
</button>;
translation.json
{
"sign-in": "sign in"
}
plurals
t("item", { count: info.count });
{
"item_one": "item",
"item_other": "items"
}
multiple namespaces useTranslation
if pass an array to useTranslation, the first namespace as the default, we can use it without pass namespace. The other namespaces, when getting data from these namespace, need to pass the namespace.
const { t } = useTranslation(["note", "message"]);
// default namespace
t("empty-description");
// other namesapces
t("save title successfully", { ns: "message" });
note.json
{
"empty-description": "No notes exists, go write your first note!"
}
message.json
{
"save title successfully": "save title successfully"
}
Trans Component
<Trans i18nKey={"success.description"} seconds={seconds}>
we will get you in after {{ seconds }}s, or click here dive in right now
</Trans>
{
"success": {
"description": "we will get you in after {{seconds}}s, or click button go home right now"
}
}
get/set current language
get current language depends on the cache config in i18.ts
I use localStorage in this article
// get current language
const currentLng = localStorage.getItem("i18nextLng");
// set current language
const { i18n } = useTranslation();
i18n.changeLanguage(item);
reference
- react-i18next: https://react.i18next.com/latest/using-with-hooks
- i18n init cache options: https://www.i18next.com/overview/plugins-and-utils#backends
- plurals: https://www.i18next.com/translation-function/plurals
Top comments (0)