- 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
September 21, 2021 11:52
-
-
Save mikeringrose/37535f859d4099ff6cf83852e9a5c7d6 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