Skip to content

Instantly share code, notes, and snippets.

@marinsagovac
Last active December 18, 2020 09:08
Show Gist options
  • Save marinsagovac/a0a02858655dd579432381e0313d74f7 to your computer and use it in GitHub Desktop.
Save marinsagovac/a0a02858655dd579432381e0313d74f7 to your computer and use it in GitHub Desktop.
npm install react-i18next i18next --save
npm install i18next-http-backend i18next-browser-languagedetector --save
Create i18nextConf.js in a root:
```
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
const fallbackLng = ['en'];
const availableLanguages = ['en', 'ar', 'fr'];
i18n
.use(Backend) // load translations using http (default public/assets/locals/en/translations)
.use(LanguageDetector) // detect user language
.use(initReactI18next) // pass the i18n instance to react-i18next.
.init({
fallbackLng, // fallback language is english.
detection: {
checkWhitelist: true, // options for language detection
},
debug: false,
whitelist: availableLanguages,
interpolation: {
escapeValue: false, // no need for react. it escapes by default
},
});
export default i18n;
```
Import these configurations into your index.js file.
import ‘./i18nextConf’;
Usage
=====
Hooks:
------
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation();// this_is_an_example is the key against translation in locales/en/translation.json file. return <h1>{t('this_is_an_example')}</h1>
}
-----------------------
Class HOC:
----------
import { withTranslation } from 'react-i18next';
class MyComponent extends Component {
render() {
const {t} = this.props
return (<h1>{t('this_is_an_example')}</h1>)
}
}
export default withTranslation()(MyComponent)
Switcher
========
import i18next from "i18next";
i18next.changeLanguage(lang);
Sandbox
=======
https://codesandbox.io/s/multi-language-pbt7g?from-embed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment