We use react-i18next for internationalization our app which is based on 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)
import { withTranslation } from 'react-i18next
You can use it in class components OR functional components
Define t inside the render function
const { t } = this.props;
A functional component gets the t
function via props.
function AboutShow ({ t }) {
}
export default withTranslation()(MyComponent);
Before:
<h1>The Fabric of My Life</h1>
After:
<h1>{t("appTitle")}</h1>
"appTitle": "The Fabric of My Life"
The keys should be the same and the values should be translated
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"
}
}