React internationalization react-intl usage

React internationalization react-intl usage

How to achieve internationalization in React? The react-intl plug-in provides a set of methods to implement react internationalization. The specific implementation is as follows~~

1. Build the react environment and download the corresponding plug-ins

By default, you have already installed nodejs. If you don’t have it installed, install it from Baidu. I won’t go into details here.

Use the official React scaffolding to build a React project. If you already have an existing React project, you can ignore this step. Then download the related dependency react-intl

npx create-react-app react-intl-demo  
npm i react-intl -S

Wait for the download to complete

Find the src folder in the project root directory and create a new folder called locale in it to store the language pack setting files; here only Chinese and English are switched, and the subsequent operations for other languages ​​are the same

insert image description here

Second, write the relevant configuration files

Find the locale intl.js file and introduce related plug-ins to encapsulate and expose them

import React, { useContext } from 'react'
import { IntlProvider } from 'react-intl' // Wrapped in the outermost layer of components that need language internationalization, just like react-redux's Provider, let components and subcomponents within components use the APIs and methods provided by react-intlimport { mainContext } from '../reducer' // Here we use useReducer to simply create one in the root directory to control the global state maintenance of the languageimport zh_CN from './cn' // Chinese packageimport en_US from './en' // English packageconst Inter = (props) => {
    // Get the default language settings. You can also use it in conjunction with some global state management such as redux Mobx or useReducer provided by react itself. const { state } = useContext(mainContext)
  const chooseLocale = (val) => { 
    let _val = val || navigator.language.split('_')[0]
    switch (_val) {
      case 'en':
        return en_US
      case 'zh':
        return zh_CN
      default:
        return zh_CN
    }
  }
  let locale = state.locale // Get locale
  let { children } = props
  // Wrap subcomponents to share react-intl's API to achieve multi-language return (
    <IntlProvider
      key={locale}
      locale={locale}
      defaultLocale='zh'
      messages={chooseLocale(locale)}
    >
      {children}
    </IntlProvider>
  )
}

export default Inter

cn.js

const zh_CN = {
    start: 'Start',
    switch: 'switch'
  }
  export default zh_CN
  

en.js

const en_US = {
    start: 'start',
    switch: 'switch'
  }
  export default en_US
  

reducer.js (create a new one in the src directory)

import React, { useReducer } from 'react'
const CHANGE_LOCALE = 'CHANGE_LOCALE'

const mainContext = React.createContext()

const reducer = (state, action) => {
  switch (action.type) {
    case CHANGE_LOCALE:
      return { ...state, locale: action.locale || 'zh' }
    default:
      return state
  }
}

const ContextProvider = (props) => {
  const [state, dispatch] = useReducer(reducer, {
    locale: 'zh'
  })
  return (
    <mainContext.Provider value={{ state, dispatch }}>
      {props.children}
    </mainContext.Provider>
  )
}

export { reducer, mainContext, ContextProvider }

3. Import related files and use them in App.js

App.js

import './App.css';
import { ContextProvider } from './reducer'
import Inter from './locale/intl'
import View from './views'

function App() {
  return (
    <ContextProvider>
      <Inter>
        <View />
      </Inter>
    </ContextProvider>
  );
}
export default App;

Fourth, create a new views directory and use related plug-ins and APIs to achieve internationalization

Create a new index.jsx file in views to try out the effect

import react, { useContext} from 'react'
import { mainContext } from '../reducer'
import { FormattedMessage } from 'react-intl'
 
function Index() {
    const { dispatch, state } = useContext(mainContext)
    const { locale } = state
    const changeLang = () => { // Change the language in the state to switch dispatch({
            type: 'CHANGE_LOCALE',
            locale: locale === 'zh' ? 'en' : 'zh'
        })
    }
    return (
        <div>
           <div>
            <FormattedMessage id="start" ></FormattedMessage>
           </div>
           <div>
                <button onClick={changeLang} > <FormattedMessage id="switch" ></FormattedMessage></button>
           </div>
        </div>
    );
}
export default Index;

The red box in the final directory is newly added

insert image description here

Just like this, a simple react internationalization is completed!
You can give it a try. If the project needs it, you can also transplant it in this way. This demo has been uploaded to GitHub: You can clone and run it by yourself at the github address

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

You may also be interested in:
  • How to introduce scss into react project
  • How to introduce Angular components in React
  • React introduces container components and display components to Vue
  • React Synthetic Events Explained
  • A brief comparison of Props in React
  • Detailed explanation of the solution for migrating antd+react projects to vite
  • Reasons and solutions for the failure of React event throttling effect
  • React implementation example using Amap (react-amap)
  • A brief introduction to React

<<:  Example of building a redis-sentinel cluster based on docker

>>:  Summary of Linux operation and maintenance from elementary to advanced knowledge points

Recommend

How to set mysql5.7 encoding set to utf8mb4

I recently encountered a problem. The emoticons o...

Super simple implementation of Docker to build a personal blog system

Install Docker Update the yum package to the late...

Summary of MySQL slow log related knowledge

Table of contents 1. Introduction to Slow Log 2. ...

5 Easy Ways to Free Up Space on Ubuntu

Preface Most people will probably perform this op...

Practical operation of using any font in a web page with demonstration

I have done some research on "embedding non-...

MySQL uses custom sequences to implement row_number functions (detailed steps)

After reading some articles, I finally figured ou...

MySQL query_cache_type parameter and usage details

The purpose of setting up MySQL query cache is: C...

How to change the root password in MySQL 5.7

Starting from MySQL 5.7, many security updates ha...

Example of using Nginx to implement port forwarding TCP proxy

Table of contents Demand Background Why use Nginx...

HTML tag dl dt dd usage instructions

Basic structure: Copy code The code is as follows:...