Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jack2jm/37584a5fabfd14ff728c0e70f851e5e3 to your computer and use it in GitHub Desktop.
Save jack2jm/37584a5fabfd14ff728c0e70f851e5e3 to your computer and use it in GitHub Desktop.
import './App.css';
import { useTranslation } from "react-i18next";
function App() {
const { t, i18n } = useTranslation();
return (
<div className="App">
{/* call name of the variable from the translation.json file to t() method */}
<p>{t('jatin')}</p>
<p>{i18n.t('jatin')}</p> //this will be used for if outside component declration
</div>
);
}
export default App;
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
// Importing translation files
import translationEN from "./locales/en/translation.json";
import translationRO from "./locales/ro/translation.json";
//Creating object with the variables of imported translation files
const resources = {
en: {
translation: translationEN,
},
ro: {
translation: translationRO,
},
};
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
// want your translations to be loaded from a professional CDN? => https://github.com/locize/react-tutorial#step-2---use-the-locize-cdn
//.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({
resources,
lng: "en", //default language
fallbackLng: "en",
debug: true,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
});
export default i18n;
Reference Link (https://medium.com/how-to-react/setup-multilingual-in-react-js-using-i18n-module-33b1bfbb57cd)
-------
1. Installation
npm install react-i18next i18next
npm i18next-browser-languagedetector //this is for autometic browser lang detactor
2. Create i18n.js file inside src.
** file code below attached.
3. now create a locales directory inside the src directory. Here we will keep our translation files in JSON format.
So after creating the directory create en and hn directory inside locales directory and then create translation.json file in
each directory.
locale/en/transation.json
{
"name": "Name",
"jatin": "Jatin"
}
// same goes multi lang locale/hi/transation.json
....
4. Just import the i18n.js file inside your index.js file.
import "./i18n";
5. use in any component
-> Import useTranslation to component
const { t, i18n } = useTranslation();
-> p>{t('jatin')}</p>
-> p>{i18n.t('jatin')}</p> //this will be used for outside component
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment