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

A brief discussion on React native APP updates

Table of contents App Update Process Rough flow c...

About the problem of writing plugins for mounting DOM in vue3

Compared with vue2, vue3 has an additional concep...

Detailed explanation of JavaScript closure issues

Closures are one of the traditional features of p...

IE conditional comments for XHTML

<br />Conditional comments are a feature uni...

Explanation of the execution priority of mySQL keywords

As shown below: from table where condition group ...

jQuery to achieve the barrage effect case

This article shares the specific code of jQuery t...

MySQL msi installation tutorial under windows10 with pictures and text

1. Download 1. Click the latest download from the...

A brief discussion on the perfect adaptation solution for Vue mobile terminal

Preface: Based on a recent medical mobile project...

MySQL 8.0.19 Installation Tutorial

Download the installation package from the offici...

A graphic tutorial on how to install MySQL in Windows

Abstract: This article mainly explains how to ins...

Native JavaScript to achieve slide effects

When we create a page, especially a homepage, we ...

What is MIME TYPE? MIME-Types type collection

What is MIME TYPE? 1. First, we need to understand...

How to deploy LNMP architecture in docker

Environmental requirements: IP hostname 192.168.1...

MySQL5.7.21 decompressed version installation detailed tutorial diagram

Since I often install the system, I have to reins...