Skip to content

Commit 443c1bb

Browse files
TRANSLATE
1 parent 9c4f6bd commit 443c1bb

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

react.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,3 +1659,77 @@ export default {
16591659
`}
16601660
`
16611661
}
1662+
1663+
1664+
1665+
// TRANSLATE I18N
1666+
1667+
// npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector --save
1668+
// https://react.i18next.com/latest/using-with-hooks
1669+
1670+
// i18n.js next to index.js
1671+
import i18n from 'i18next';
1672+
import { initReactI18next } from 'react-i18next';
1673+
import Backend from 'i18next-http-backend';
1674+
import LanguageDetector from 'i18next-browser-languagedetector';
1675+
i18n
1676+
.use(Backend)
1677+
.use(LanguageDetector)
1678+
.use(initReactI18next)
1679+
.init({
1680+
fallbackLng: 'en',
1681+
debug: true,
1682+
interpolation: {
1683+
escapeValue: false,
1684+
}
1685+
});
1686+
export default i18n;
1687+
1688+
// update index.js with i18n import
1689+
import './i18n';
1690+
1691+
// add translation to App.js
1692+
import React, { Suspense } from 'react';
1693+
export default function App() {
1694+
return (
1695+
<Suspense fallback="loading">
1696+
<MyComponent />
1697+
</Suspense>
1698+
);
1699+
}
1700+
1701+
// create translation files (./public/locales/en/translation.json)
1702+
{
1703+
"text": "This text comes from translation",
1704+
"translations": "Translations",
1705+
"anything": "Anything",
1706+
"withVariable": "With a variable of: {{var}}",
1707+
"item_one": "Item",
1708+
"item_other": "Items"
1709+
}
1710+
1711+
// add translation to a component
1712+
import { useState } from 'react';
1713+
import { useTranslation } from 'react-i18next';
1714+
function MyComponent() {
1715+
const { t, i18n } = useTranslation();
1716+
const [lang, setLang] = useState(i18n.language);
1717+
function changeLang(lng) {
1718+
setLang(lng);
1719+
i18n.changeLanguage(lng);
1720+
}
1721+
return (
1722+
<div className="App">
1723+
<h1>
1724+
i18n {lang.toUpperCase()} {t('translations')}
1725+
</h1>
1726+
<h2>{t('text')}</h2>
1727+
<p>{t('anything')}</p>
1728+
<p>{t('withVariable', { var: 40 })}</p>
1729+
<p>{t('item', { count: 1 })}</p>
1730+
<p>{t('item', { count: 2 })}</p>
1731+
<button onClick={() => changeLang('en')}>EN</button>
1732+
<button onClick={() => changeLang('fr')}>FR</button>
1733+
</div>
1734+
);
1735+
}

0 commit comments

Comments
 (0)