React implements internationalization

React implements internationalization

React is a popular JavaScript library used for building web applications. React does a great job with multi-language support, enabling applications that are easily localized and internationalized.

Here are the steps to implement internationalization in React:

  1. Install and configure the React Internationalization (i18n) library

The React Internationalization library is a JavaScript library for localizing React applications. To install the library, use the following command:

npm install --save react-i18next i18next
  1. Create localization files

Create localization files with all languages. Alternatively, you can use existing localization files. To create localization files, use the following command:

mkdir i18n
touch i18n/locales.json

In the locales.json file you can define localized translations for all languages. For example:

{
    
    
  "en": {
    
    
    "greeting": "Hello!",
    "message": "This is a message"
  },
  "fr": {
    
    
    "greeting": "Salut!",
    "message": "C'est un message"
  },
  "ja": {
    
    
    "greeting": "こんにちは!",
    "message": "これはメッセージです"
  }
}
  1. Configuring the React Internationalization (i18n) library

In a React application, you need to configure the React Internationalization library. You can add the following code to your application:

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

import locales from './i18n/locales.json';

const resources = {
    
    
  ...locales,
};

i18n.use(initReactI18next).init({
    
    
  resources,
  fallbackLng: 'en',
  ns: ['translations'],
  defaultNS: 'translations',
  interpolation: {
    
    
    escapeValue: false,
  },
});

In the code above, we import locales as a JavaScript object. We pass this object to i18n’s init() method. The init() method takes the following options:

  • resources: source of localized translations.
  • fallbackLng: The fallback language that should be used if the current language is not available.
  • ns: namespace. In this example, we use translations.
  • defaultNS: default namespace. In this example, we use translations.
  • interpolation: Options on how placeholders are interpreted.
  1. Use translation files

In a React application, you can add the following code to the components that need to be localized:

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

function HelloWorld() {
    
    
  const {
    
     t } = useTranslation(['translations']);
  return (
    <div>
      <h1>{
    
    t('greeting')}</h1>
      <p>{
    
    t('message')}</p>
    </div>
  );
}

In the above code, we use the useTranslation hook to get a translation function t from the i18n library. We use the t function to obtain the localized translations of greeting and message.

おすすめ

転載: blog.csdn.net/NIKKT/article/details/129954585