Home > AI > Frontend > react-i18next >

localization

Step 1: installation

npm install i18next react-i18next

Step 2: Configure i18next

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

// the translations
// (tip move them in a JSON file and import them)
const resources = {
    ch: {
        translation: {
            "课程": "课程"
        }
    },
    en: {
        translation: {
            "课程": "Courses"
        }
    },
    hi: {
        translation: {
            "课程": "नमस्ते"
        }
    }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

  export default i18n;

import in the index.js

import React, { Component } from "react";
import ReactDOM from "react-dom";
import './i18n';
import App from './App';

// append app to dom
ReactDOM.render(
  <App />,
  document.getElementById("root")
);

Step 3: Translate your content

Using the render prop (working, for class component)

import React from 'react';

// the render prop
import { Translation } from 'react-i18next';

export default function MyComponent () {
  return (
    <Translation>
      {
        t => <h1>{t('Welcome to React')}</h1>
      }
    </Translation>
  )
}

Using the Trans component (working, the simplest)

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

export default function MyComponent () {
  return <Trans><H1>Welcome to React</H1></Trans>
}

Official support:

https://react.i18next.com/guides/quick-start#configure-i-18-next

Other dependecies

npm i i18next-browser-languagedetector
npm i i18next-http-backend

Leave a Reply