Examples of REACT-INTL implementation of multi-lingual

Source: Internet
Author: User
Tags i18n intl
This article mainly introduces the REACT-INTL implementation of multi-language sample code, small series feel very good, and now share to everyone, but also for everyone to do a reference. Follow the small series together to see it, hope to help everyone.

Recently added language internationalization features to your project.

Language internationalization, it is also said to be language localization, in fact, is to add multiple languages for the Web app, our project currently contains the Chinese version and English version, supposedly "verbatim replacement" is not much of a matter, but, so low approach, rich way?

At first, I was thinking about the traditional add config file for the entire project, depending on the language and region, loading different config files, you can achieve the purpose of the interface language switching. Of course, it is because the idea is too naïve, so it is called the "first" idea. The internationalization of language is not only to translate UI text into another language, but also include date & time display, digital display (every 3 digits of a comma in English environment: 1,000), quantifier display (an apple is Apple, two apples should be apples), There is even a case where a variable is inserted in the middle of the string ("Eat {count} chicken legs for lunch today") ...

So this is not just a simple character substitution problem, and we want to easily export a directory, put it in Word or page, to other colleagues to follow the translation work, this is very important!! Do you want the product manager to change it directly in the code? Or do you want a search for a replacement? If you do not think clearly, believe me, you'll pay for this.

As a index.html, you certainly don't want to add a line <Script> quote to it? In addition, the text in the UI is all the students who use the picture, please stand up and roll. If you want to use an elegant import something from somewhere in a react project, then replace the text in the interface with the < capitalize/> component, and finally realize the internationalization of the language with a simple configuration, Then let's use React-intl.

React do internationalization, I recommend using REACT-INTL, this library provides React components and APIs two ways to format dates, numbers and strings. Know this library, so let's start using it.

Component usage

In order to be more in harmony with react, we can use components in a way

1. Installation

NPM Install React-intl--save

2. Adding references

Import {intlprovider, addlocaledata} from ' React-intl ';

3. Add a Locale profile

Zh-cn.js

Const ZH_CN = {' Intl.hello ': "Hello", ' intl.name ': ' My name is {name} '} export default ZH_CN;

En-us.js

Const EN_US = {' Intl.hello ': "Hello", ' intl.name ': ' My name is {name} '} export default en_US;

4. Using <intlprovider/>

This component is used to set the context of the i18n, which wraps the root component of the application so that the entire application is configured in the context of the i18n.
The main two configuration items are: loacle The current language environment messages the contents of the current language.

To dynamically switch languages, we need to change these two configurations dynamically.

Import ZHCN from './locale/zh.js ';  Import i18n config file import enus from './locale/en.js '; Addlocaledata ([... en,. ... en]); Export default class Root extends Component {  static proptypes = {    store:PropTypes.object.isRequired,    history:PropTypes.object.isRequired  }  render () {    const {store, history} = This.props;    Return (      <intlprovider locale= ' zh ' messages={zhcn}>        <provider store={store}>          <router history={history}>          </Router>        </Provider>      </IntlProvider>    )  }}

5. Using <formattedmessage/>

Basic usage

<formattedmessage id= "Intl.hello" defaultmessage={' Hello '}/>

If the current locale is Chinese, it will display Hello, if it is an English environment, it will display hello.

Dynamic Transfer value

<formattedmessage  id= "Intl.name"  values={{name: <b>{name}</b>}}/>

When we define Intl.name, the template uses {name}, which means we can dynamically pass values, and we can pass a JSON object through the Values property in Formattedmessage, which will dynamically display our content.

6. Other component usage

RACT-INTL provides us with a wealth of components, can help us to deal with the string, time, date, we can view the API, if you do not understand the place, I can leave a message.

API usage

Sometimes we may need to do the internationalization in the code dynamically, which requires the dynamic API. Let me briefly explain how to use

1. Import Injectintl

Import {injectintl, formattedmessage} from ' React-intl ';

2. Inject in the component

Export default Connect (mapstatetoprops,mapactioncreators) (Injectintl (APP))

I used the redux in the project, when injected should be to the above, if you do not use Redux, only need to export Defuault injectintl (APP)

3. Using the Intl Object

We pass the second injection, and now we get a intl object on the props of the component, it provides a method that basically corresponds to the component we described above, and when we want to display the string, we can use the FormatMessage method:

const {INTL} = This.props; Let TMP = Intl.formatmessage ({id: ' intl.name '},{name: ' Joe '});

FormatMessage The first parameter can pass in the ID, the second parameter passed to the values, more detailed understanding, see the API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.