Skip to content

Instantly share code, notes, and snippets.

@samyarmodabber
Last active March 14, 2024 07:21
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 samyarmodabber/ab1ec4e985fe44562434a85cee9000c1 to your computer and use it in GitHub Desktop.
Save samyarmodabber/ab1ec4e985fe44562434a85cee9000c1 to your computer and use it in GitHub Desktop.

i18next_eco

A Guied to use react-i18next in your component

Intro

We use react-i18next for internationalization our app which is based on i18next.

What we did for config i18next

  1. Add i18n.js (src->react) and import it in index.js Read more
  2. Add two JSON files, dk.json and en.json (src->react->locales)
  3. 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"
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment