How to understand multilingual internationalization?

The drop-down section in the image already makes it clear what multilingual internationalization is.

Personal understanding: it is that we can switch the language type on the website to achieve the same function in different languages.

The react – i18next is introduced

React-i18next is a powerful react/React Native internationalization framework based on i18Next’s React plugin.

Install dependencies

NPM install react-i18Next i18Next --save NPM install react-i18Next i18Next --save The i18Next is the core that provides all the translation functionality, and the React-i18Next is designed to be used with React with some additional functionality.Copy the code

Project file structure

Project configuration

1. Local JSON data initialization (create simplified, traditional and English JSON files)

The data structure of zh-cn. Json file is the same as that of traditional and English characters, but the content is different.Copy the code
{" home ": {" title" : "home page", "content" : "I'm home,"}, "about" : {" title ":" about us ", "content" : "I am about our"}}Copy the code

Create a react-i18next-config.js file that configures react-i18Next

import i18n from "i18next"; import { initReactI18next } from "react-i18next"; // this is an i18next languagedetector plugin that detects the user's language in the browser. For details, visit: https://github.com/i18next/i18next-browser-languageDetector import LanguageDetector from 'i18next-browser-languagedetector'; // Import cn from './locales/zh-cn. Json 'import hk from './locales/ zh-hk from './locales/en-us.json' const resources = { cn: { translation: cn }, hk: { translation: hk }, en: { translation: en }, }; Use (LanguageDetector) // Sniff the current browser language en -CN. Use (initReactI18next) // pass the i18n down to react-i18next. Init ({// initialize Resources, // local multilanguage data fallbackLng: "cn", // Default language detection for the current environment: {caches: ['localStorage', 'sessionStorage', 'cookie'], } }) export default i18nCopy the code

3. Then introduce react-i18next-config.js into the app.js component

import i18n from './react-i18next-config'

In this case, react-i18Next and i18Next can be applied to the App component and all its child components.Copy the code

4. Default language and default data

After the project is initialized, the default language of the user's browser is zh-cn according to the react-i18next-config.js file on resources:Copy the code
"zh-CN": {
    translation: './locales/zh-cn.json'
  },
  "zh-HK": {
    translation: './locales/zh-HK.json'
  },
  "en-US": {
    translation: './locales/en-us.json'
  },
Copy the code
/locales/zh-cn. Json./locales/zh-cnCopy the code

4. Develop and select switching language components

<div> <label> <select value={language} onChange={(e)=>changeLanguage(e)}> <option value=" zh-cn "> </option> <option value=" en-us "> </option> </option> </select> </div>Copy the code
When we make a language switch, the changeLanguage method in the component is called. The call to this method does several things: Const [language,setLanguage] = useState(' zh-cn ') setLanguage(useState(' zh-cn ') setLanguage(useState(' zh-cn ')) Executes the changeLanguage (currently selected language type) method on the i18n exported by react-i18next-config.js. /locales/zh-cn. Json '}, "zh-hk ": {translation: './locales/zh-cn. './locales/en-us.json'}, "en-us ": {translation: './locales/en-us.json'} Update the value of i18nextLng in localStorageCopy the code

5. Introduction of i18next-Browser-LanguageDetector plug-in

After installing the i18next-browser-LanguageDetector plug-in, you can detect that the current browser language is zh-CN. In this case, i18nextLng is set to zh-cn in localStorage. So why is this stored in localStorage? Why is the key i18nextLng?Copy the code

The above code is the source code of i18next-browser-LanguageDetector plug-in. We can clearly see that the plug-in stores the browser's user language (zh-cn) to localStorage by default and sets the key name i18nextLng

Custom Configuration

If we need customization, we can configure it through the Detector Options in the official document, for example: After initializing the project, we not only want to store i18nextLng in localStorage, but also want to store i18nextLng in sessionStorage and cookies. To do this, run the following command: detection: {caches: ['localStorage', 'sessionStorage', 'cookie'],} Place the preceding configuration in the i18N init object.Copy the code

LocalStorage Specifies the functions of the i18nextLng

As we all know, localStorage is not as the page refresh, label closed caused by data loss, that is to say, when we refresh the page, we can still get the last user selected language type, and according to the language type to load the corresponding JSON file data.Copy the code

For more configuration, visit the i18next-Browser-LanguageDetector official documentation: github.com/i18next/i18…

How to use React-i18Next to render, and then realize the page multi-language switch?

  1. useTranslation (hook)
Note: useTranslation() must be used in the function component otherwise it will cause an hooks error.Copy the code
 const { t } = useTranslation()
 <NavLink to="/home">{t('home.title')}</NavLink>
Copy the code
  1. Translation (render prop)
import {Translation} from 'react-i18next'

<Translation>
  {(t) => <h3>{t("about.content")}</h3>}
</Translation>
Copy the code
  1. WithTranslation (HOC) High-level component mode
React-i18next internally encapsulates a high-level component called withTranslation. We need to use this high-level component to wrap our own components onceCopy the code
import { withTranslation } from 'react-i18next'; Class Home extends Component {render() {const {t} = this.props return (<div> <h3>{t("home.content")}</h3> < / div >)}} / / function component const Home = ({t}) = > {return (< div > < h3 > {t} (" Home. The content ") < / h3 > < / div >)} / export/components:  export default withTranslation()(Home)Copy the code

Project implementation

This article is on GithubGithub.com/dabaoRain/r…

Reference documentation

react.i18next.com/

www.i18next.com/

Github.com/i18next/rea…

Github.com/i18next/i18…

The author’s understanding of React-i18Next is a basic entry level. Please kindly point out the mistakes in the understanding or use of react-i18Next in the article. If there are any questions that need to be added or commented, the author will be grateful. Typesetting code word is not easy, think it is helpful to you, please help a like it!