Library i18n
Commonly used library and approach for localization.
Installation
-
Install packages
1yarn 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 addedi18n.ts
-
Put translation files in
public/locales/${LOCALIZATION_NAME}/translation.json
Usage
Through special hook in components
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// 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)
1 2 3 4 5 6 |
// 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:
1 |
localStorage.setItem("i18nextLng", "cn") |
Refresh the page after to see new site localization applied