React internationalization react-i18next detailed explanation

React internationalization react-i18next detailed explanation

insert image description here

Introduction

react-i18next is a powerful internationalization framework based on i18next . It can be used in react and react-native applications. It is currently a very mainstream internationalization solution.

i18next has the following advantages:

  • Based on i18next, it is not limited to react. You can learn it once and use it in other places.
  • Provides multiple components for internationalization in hoc, hook and class scenarios
  • Suitable for server-side rendering
  • It has a long history, started in 2011, which is older than most front-end frameworks.
  • Because of its long history, it is more mature. There is no internationalization problem that i18next cannot solve.
  • There are many plugins supported, for example, plugins can be used to detect the current system's locale and load translation resources from the server or file system

Install

You need to install both i18next and react-i18next dependencies:

npm install react-i18next i18next --save
or
yarn add react-i18next i18next --save


Configuration

Create a new i18n folder under src to store internationalization related configurations

Create three new files in i18n :

  • config.ts : Initialize i18n and configure plugins
  • en.json : English language configuration file
  • zh.json : Chinese language configuration file

insert image description here

en.json

{
    "header": {
        "register":"Register",
        "signin":"Sign In",
        "home": "Home"
    },
    "footer": {
        "detail" : "All rights reserved @ React"
    },
    "home": {
        "hot_recommended": "Hot Recommended",
        "new_arrival": "New arrival",
        "joint_venture": "Joint Venture"
    }
}

zh.json

{
    "header": {
        "register":"Register",
        "signin":"Login",
        "home": "Home"
    },
    "footer": {
        "detail" : "Copyright @ React"
    },
    "home": {
        "hot_recommended": "Hot Recommended",
        "new_arrival": "New arrival",
        "joint_venture": "Joint venture"
    }
}

config.ts

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import translation_en from './en.json';
import translation_zh from './zh.json';

const resources = {
    en:
        translation: translation_en,
    },
    en: {
        translation: translation_zh,
    },
};

i18n.use(initReactI18next).init({
    resources,
    lng: 'zh',
    interpolation:
        escapeValue: false,
    },
});

export default i18n;

use

Reference Profile

Reference the i18n configuration file in index.tsx : import './i18n/config';

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import './i18n/config'; // Reference configuration file ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById('root')
);

Use in components

Method 1

Use the withTranslation high-order function (HOC) in the class component to complete the data injection of the language configuration

import React from 'react';
import styles from './Home.module.css';

//Introduce HOC high-order function withTranslation and i18n ts type definition WithTranslation 
import { withTranslation, WithTranslation } from "react-i18next"

class HomeComponent extends React.Component<WithTranslation> {
    render() {
        const { t } = this.props;
        return <>
           <h1>{t('header.home')}</h1>
           <ul>
               <li>{t('home.hot_recommended')}</li>
               <li>{t('home.new_arrival')}</li>
               <li>{t('home.joint_venture')}</li>
           </ul>
        </>
    }
}

export const Home = withTranslation()(HomeComponent); // Use the withTranslation high-order function to complete the data injection of language configuration

Method 2

Use useTranslation hook in functional components to handle internationalization

import React from 'react';
import { useTranslation, Trans } from 'react-i18next'

export const Home: React.FC = () => {
    const { t } = useTranslation()
    return (
		<div>
			<h1>{t('header.home')}</h1>
			<ul>
				<li>{t('home.hot_recommended')}</li>
				{/* There is another way */}
				<li><Trans>home.new_arrival</Trans></li>
			</ul>
		</div>    
    );
};

Switch language

import i18n from 'i18next';

const changeLanguage= (val) => {
	i18n.changeLanguage(val); // val parameter value is 'en' or 'zh'
};

or

import React from 'react';
import { useTranslation } from 'react-i18next'

export const Home: React.FC = () => {
    const { t, i18n } = useTranslation()
    return (
		<button onClick={()=>i18n.changeLanguage(i18n.language=='en'?'zh':'en')}>{i18n.language=='en'?'zh':'en'}</button>
    );
};

This is the end of this article about React internationalization react-i18next. For more relevant React internationalization react-i18next content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • react-intl implements React internationalization and multi-language method
  • Detailed explanation of the use of react-i18n-auto, a plugin for internationalization of react
  • React internationalization implementation code example

<<:  Sample code for achieving three-dimensional picture placement effect with pure CSS

>>:  Summary of MySQL log related knowledge

Recommend

Vue2.x responsiveness simple explanation and examples

1. Review Vue responsive usage​ Vue responsivenes...

Detailed explanation of HTML form elements (Part 1)

HTML forms are used to collect different types of...

Complete steps to enable gzip compression in nginx

Table of contents Preface 1. Configure gzip compr...

How to Learn Algorithmic Complexity with JavaScript

Table of contents Overview What is Big O notation...

Tomcat source code analysis of Web requests and processing

Table of contents Preface 1. EndPoint 2. Connecti...

Deleting files with spaces in Linux (not directories)

In our daily work, we often come into contact wit...

Detailed explanation of js's event loop event queue in the browser

Table of contents Preface Understanding a stack a...

HTML fixed title column, title header table specific implementation code

Copy code The code is as follows: <!DOCTYPE ht...

Implementation of MySQL multi-version concurrency control MVCC

Transaction isolation level settings set global t...

How to analyze MySQL query performance

Table of contents Slow query basics: optimizing d...

Detailed graphic explanation of mysql query control statements

mysql query control statements Field deduplicatio...

Let's talk about the difference between containers and images in Docker

What is a mirror? An image can be seen as a file ...

Detailed explanation of application scenarios of filters in Vue

filter is generally used to filter certain values...