Back to Astron Agent

I18N Implementation Guide

console/frontend/I18N.md

1.0.62.3 KB
Original Source

I18N Implementation Guide

This project has been set up with internationalization (i18n) using the i18next and react-i18next libraries.

Structure

  • src/i18n/index.ts - Main i18n configuration
  • src/locales/en.js - English translations
  • src/locales/zh.js - Chinese translations
  • src/hooks/useTranslation.ts - Custom hook combining react-i18next with our locale store
  • src/components/LanguageSwitcher/index.tsx - Language switcher component

How to Use

Basic Translation

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

const MyComponent = () => {
  const { t } = useTranslation();

  return <div>{t('keyName')}</div>;
};

Advanced Usage with Parameters

tsx
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';

const MyComponent = () => {
  const { t } = useTranslation();
  const currentDate = dayjs();

  return <div>{t('myMessage', { ts: currentDate })}</div>;
};

Changing Languages

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

const MyComponent = () => {
  const { i18n } = useTranslation();

  const changeLanguage = lng => {
    i18n.changeLanguage(lng);
  };

  return (
    <div>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('zh')}>中文</button>
    </div>
  );
};

Using Our Custom Hook

Our custom hook combines i18next with our Zustand store:

tsx
import useTranslation from '@/hooks/useTranslation';

const MyComponent = () => {
  const { t, locale, toggleLocale, isZh, isEn } = useTranslation();

  return (
    <div>
      <h1>{t('title')}</h1>
      <button onClick={toggleLocale}>
        {isZh ? 'Switch to English' : '切换到中文'}
      </button>
    </div>
  );
};

Adding New Translations

  1. Add your new translation keys to both src/locales/en.js and src/locales/zh.js
  2. Follow the same format as existing translations
  3. Use the keys in your components with t('yourNewKey')

Language Switcher

The language switcher component is available at src/components/LanguageSwitcher/index.tsx and can be imported and used anywhere in the application.

tsx
import LanguageSwitcher from '@/components/LanguageSwitcher';

const MyComponent = () => {
  return (
    <div>
      <h1>My Page</h1>
      <LanguageSwitcher />
    </div>
  );
};