Internationalization (i18n)
Learn how to implement multi-language support in your application
Directory Structure
The localization files are organized in the src/locales directory
src/locales/
├── i18n.ts # Main configuration file
├── context.tsx # React context for translations
├── use-locales.ts # Custom hook for language selection
├── use-translate.ts # Custom hook for translations
├── en.json # English translations
├── fr.json # French translations
└── de.json # German translations (example)
Adding Translations
Create translation files for each language using a consistent structure
src/locales/en.json
{
"demo": {
"title": "English",
"introduction": "English version"
},
"app": {
"name": "KimiStores App",
"version": "Version"
},
"auth": {
"login": "Login",
"register": "Register"
},
"navigation": {
"home": "Home",
"dashboard": "Dashboard"
}
}
src/locales/fr.json
{
"demo": {
"title": "Français",
"introduction": "Version française"
},
"app": {
"name": "KimiStores App",
"version": "Version"
},
"auth": {
"login": "Connexion",
"register": "S'inscrire"
},
"navigation": {
"home": "Accueil",
"dashboard": "Tableau de bord"
}
}
Basic Usage
How to use translations in your components
import { useTranslate } from 'src/locales';
function MyComponent() {
const { t } = useTranslate();
return (
<>
<Typography variant="h1">{t('app.name')}</Typography>
<Typography variant="body1">{t('demo.introduction')}</Typography>
{/* Nested keys */}
<Button>{t('auth.login')}</Button>
</>
);
}
Language Switcher
Implementing a language selection component
import { useLocales, useTranslate } from 'src/locales';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Typography from '@mui/material/Typography';
function LanguageSwitcher() {
const { t, onChangeLang } = useTranslate();
const { allLang, currentLang } = useLocales();
return (
<Box sx={{ p: 3 }}>
<Typography variant="h6" sx={{ mb: 2 }}>
{t('demo.title')}
</Typography>
<RadioGroup
row
value={currentLang.value}
onChange={(event) => onChangeLang(event.target.value)}
>
{allLang.map((lang) => (
<FormControlLabel
key={lang.label}
value={lang.value}
label={lang.label}
control={<Radio />}
/>
))}
</RadioGroup>
</Box>
);
}
References
Useful resources for internationalization