- Published on
A Guied to use react-i18next
- Authors
Introducing
We use react-i18next for internationalization our app which is based on i18next.
What we did for config i18next
- Add i18n.js (src->react) and import it in index.js Read more
- Add two JSON files, dk.json and en.json (src->react->locales)
- Add ChangeLanguageBtn components for toggle the language (src->react->components)
How you shoud apply for a components
1. Import withTranslation from react-i18next
import { withTranslation } from 'react-i18next
2. Add function t
You can use it in class components OR functional components
A) Class Components
Define t inside the render function
const { t } = this.props
B) Functional Components
A functional component gets the t
function via props.
function AboutShow({ t }) {}
3. Export your component by withTranslation
export default withTranslation()(MyComponent)
4. Change your static text to a dynamic one
Before:
<h1>The Fabric of My Life</h1>
After:
<h1>{t('appTitle')}</h1>
5. Add key-value to both json files(en.json and dk.json)
"appTitle": "The Fabric of My Life"
The keys should be the same and the values should be translated
Example for nested keys
For each espesial part we use nested keys and use .
(dot). Inside keys you can't use .
. For separation use _
, /
,-
instead.
Below is an example for "How to Participate" part.
- The code should be like this:
<h2>{t('howTo.topic1.title')}</h2>
- and add these lines: in en.json you should add like this:
"howTo": {
"title": "How to Participate",
"intro": "Text",
"topic1": {
"title": "Questionnaire",
"content": "Text"
},
"topic2": {
"title": "How to Record your story",
"content": "Text"
}
}
in dk.json you should add like this:
"howTo": {
"title": "Sådan deltager du",
"intro": "Tekst",
"topic1": {
"title": "Spørgeskema",
"content": "Tekst"
},
"topic2": {
"title": "Sådan optager du din historie",
"content": "Tekst"
}
}