Tutorial github link:
https://github.com/zarrukh-jurakulov/i18next-translation-demo
Hello everyone! In this tutorial we learn how to translate languages to another. Firstly we create new project :
npx create-react-app i18next-translation-demo
.
Firstly we install npm i i18next i18next-browser-languagedetector react-i18next
libraries. Then we open locales folder. In locales folder we create en folder for english language and ru for russian language. In both of folder we create translation.json json file.
In en folder of translation.json file we write some codes:
{
"title": "Welcome to learning i18next library",
"part1": "Lets start learning",
"part2": "Click here !"
}
In ru folder of translation.json file we write some codes:
{
"title": "Добро пожаловать в изучение библиотеки i18next",
"part1": "Начнем учиться",
"part2": "Кликните сюда !"
}
Create i18n file and write:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import translationEN from "./locales/en/translation.json";
import translationDE from "./locales/ru/translation.json";
import detector from "i18next-browser-languagedetector";
// the translations
const resources = {
en: {
translation: translationEN,
},
de: {
translation: translationDE,
},
};
i18n
.use(detector)
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
fallbackLng: "en", // use en if detected lng is not available
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false, // react already safes from xss
},
});
export default i18n;
In App folder we write:
import React from "react";
import { useTranslation } from "react-i18next";
import i18n from "./i18n";
import "./App.css";
// the hoc
function App() {
const { t } = useTranslation();
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<div>
<button onClick={() => changeLanguage("en")}>english</button>
<button onClick={() => changeLanguage("de")}>russian</button>
<h1>{t("title")}</h1>
<h3>{t("part1")}</h3>
<h3>{t("part2")}</h3>
<a href='https://www.i18next.com/'>https://www.i18next.com/</a>
</div>
);
}
export default App;
Top comments (0)