Skip to content

Instantly share code, notes, and snippets.

@mikeringrose
Created September 21, 2021 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeringrose/37535f859d4099ff6cf83852e9a5c7d6 to your computer and use it in GitHub Desktop.
Save mikeringrose/37535f859d4099ff6cf83852e9a5c7d6 to your computer and use it in GitHub Desktop.

React Internationalization

  1. Initialize i18next and pass down react-i18next.
  2. Simplest usage is to use the useTranslation hook
  3. Use the Render prop
  4. The Trans component allows one to render a whole JSX tree
import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import i18n from 'i18next';
import {
useTranslation,
initReactI18next,
withTranslation,
Translation,
Trans,
} from 'react-i18next';
i18n.use(initReactI18next).init({
resources: {
en: {
translation: {
'Welcome to React': 'Welcome to React and react-i18next',
'HOC Text': 'Text rendered with the HOC',
},
},
},
lng: 'en',
fallbackLng: 'en',
interpolation: {
escapeValue: false,
},
});
// - Higher Order Component (HOC)
const HOCComponent = ({ t }) => {
return <span>{t('HOC Text')}</span>;
};
const WithTranslation = withTranslation()(HOCComponent);
// - Render Prop
const RenderComponent = () => {
return (
<Translation>{(t) => <span>{t('Welcome to React')}</span>}</Translation>
);
};
// - Trans Component
const TransComponent = () => {
const name = 'Mike';
return (
<Trans>
<span>
Welcome <em>{name}</em> to the world
</span>
</Trans>
);
};
const App = () => {
const { t } = useTranslation();
return (
<Suspense>
<ul>
<li>{t('Welcome to React')}</li>
<li>
<WithTranslation />
</li>
<li>
<RenderComponent />
</li>
<li>
<TransComponent />
</li>
</ul>
</Suspense>
);
};
ReactDOM.render(<App />, document.querySelector('#root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment