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-backendTake a look at configuration file config/i18n/i18n.ts. Include it to your project somewhere
In
index.tsximport previously addedi18n.tsPut 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
Related
Posts
How I Connected React Components to External JS: A Developer's Story
As a developer, I needed to trigger a React modal from a SharePoint Ribbon button, bridging classic JS and modern React. This post explains the challenge, the solution using the global window object, and how I made React state accessible from outside the bundle.
Configuring Storybook for React.js Projects
A step-by-step guide to setting up Storybook in your React.js project, including configuration tips, code examples, and best practices for building a component library.
Solving Import Path Hell in Create React App: Aliases with CRACO or react-app-rewired
A practical guide to setting up import path aliases in Create React App projects using CRACO or react-app-rewired, with step-by-step configuration examples.
Open for contract collaboration
I am available for contract-based collaboration. If you have an interesting project idea, schedule a call via Calendly.
Schedule a 30-min call