- Initialize i18next and pass down react-i18next.
- Simplest usage is to use the
useTranslation
hook - Use the Render prop
- The Trans component allows one to render a whole JSX tree
Created
April 12, 2021 01:08
-
-
Save mikeringrose/099bef67358b50f928aa33f91ca9ddfb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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