React.js i18n: Localization Setup and Usage Guide

Published on
2 mins read
--- views

Library i18n

Commonly used library and approach for localization.

Installation

  • Install packages

    yarn add i18next i18next-browser-languagedetector i18next-xhr-backend
    
  • Take a look at configuration file config/i18n/i18n.ts. Include it to your project somewhere

  • In index.tsx import previously added i18n.ts

  • Put translation files in public/locales/${LOCALIZATION_NAME}/translation.json

Usage

Through special hook in components
import { useTranslation } from 'react-i18next';
///...

const Component: React.FC = () => {
  const { t } = useTranslation();

  ///...
  return (
    <TextField
      fullWidth
      type="email"
      label={t('Email address')}
      InputLabelProps={{
        shrink: true
      }}
      {...getFieldProps('email')}
      error={Boolean(touched.email && errors.email)}
      helperText={touched.email && errors.email}
    />
  )
}
Components with parameters binding
    // in functional component
    <Trans i18nKey="View all images" values={{ total }} />

    // in locales/en/translation.json
    {
      //...
      "View all images": "View all {{total}} images",
      //...
    }

    // in locales/cn/translation.json
    {
      //...
      "View all images": "查看所有 {{total}} 張圖片",
      //...
    }
Directional way, through utility

This is useful if you have string to localize in some objects (not functional components)

// importing file from ./config/18n/i18n.ts
import i18n from '~/utils/i18n';

const messages = {
  hello: i18n.t('world'),
};

Tips and tricks

For changing translation, you have to change value in browser local storage named i18nextLng

or use this command in console:

localStorage.setItem('i18nextLng', 'cn');

Refresh the page after to see new site localization applied