preface

I18n (from the first and last characters I and n of the English word internationalization, with 18 being the middle character) is short for “internationalization.”

In React, i18Next is used to support I18N. This article explains how to use i18Next in React-typescript projects.

As usual, let’s share the repo for this document:

Gitlab.com/yafeya/reac…

1. Install dependencies

This document and Demo builds on previous documents in this series. To support i18Next in an existing project, you first need to install the dependencies by executing the following code.

npm install i18next i18next-browser-languagedetector react-i18next
Copy the code

2. Use resources

First add i18n. TSX, zh.json, and en.json. Zh. json stores all Chinese resources, and en.json stores all English resources.

I18n.tsx is used to use these two font files and perform some basic Settings.

// i18n.tsx
import i18n from "i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import enResources from "./en.json";
import zhResources from "./zh.json";
import { initReactI18next } from 'react-i18next';

const DETECTION_OPTIONS = {
  order: ['path'.'querystring']
}

i18n.use(LanguageDetector) // Get the current browser language
.use(initReactI18next) 
.init({
  / / use the option
  detection: DETECTION_OPTIONS,
  // Resource files
  resources: {
    en: {
      translation: enResources,
    },
    zh: {
      translation: zhResources,
    },
  },
  // fallbackLng will be used if language Settings cannot be found
  fallbackLng: "zh".debug: false.interpolation: {
    escapeValue: false,}})export default i18n;
Copy the code

3. AppThe introduction ofi18n

// App.tsx
// ...
import '.. /i18n/i18n';

export class App extends Component {
    / /...
}
Copy the code

Use 4.translation

Create a New Translation Component to introduce translatable resources.

Generally, there are three ways to translate:

  • t('testing')
  • <Trans>testing</Trans>
  • <Translation>{t => <div>{t('thirdWay')}</div>}</Translation>
// translation.tsx

let { t, i18n } = useTranslation();
// ...
<div className='translationWrapper'>
    <div className='translationGroup'>
        <label>{t('firstWay')}</label>
        <label>{t('testing')}</label>
    </div>
    <div className='translationGroup'>
        <label>
            <Trans>secondWay</Trans>
        </label>
        <label>
            <Trans>testing</Trans>
        </label>
    </div>
    <div className='translationGroup'>
        <label>
            <Translation>{t => <div>{t('thirdWay')}</div>}</Translation>
        </label>
        <label>
            <Translation>{t => <div>{t('testing')}</div>}</Translation>
        </label>
    </div>
</div>
Copy the code

5. Switch languages

The current language can be modified by calling i18N.Changelanguage (language).

function onclick() {
    let targetLanauge = i18n.language === 'en' ? 'zh' : 'en';
    i18n.changeLanguage(targetLanauge);
}

// ...
<div className='translationGroup'>
    <button className='btn btn-primary' onClick={()= > onclick()}>{t('switchLanguage')}</button>
</div>
Copy the code

6. SEO Friendly

When using i18N, make sure your app is SEO Friendly, which means you need to give your clients a URL that accesses the right language.

For example, for Chinese users, you should give the URL http://some-domain/zh, and for English users, you should give the URL http://some-domain/en.

The i18Next does a good job with seo-friendly support. You can set the order of language monitoring by setting init-options.

// i18n.tsx

// path: detects language information based on the URL
// queryString: queryString to detect language information,? lng=language
// Many other methods are supported, but none are seO-friendly
const DETECTION_OPTIONS = {
  order: ['path'.'querystring']
}

i18n.use(LanguageDetector) // Get the current browser language
.use(initReactI18next) 
.init({
  detection: DETECTION_OPTIONS,
  // ...
  })
Copy the code

After setting the language information, you can view the result in DevTools -> Application -> localStorage.