i18n and react-i18next
- React course
- Advanced
- Lesson 43/56
- 4 min
Learn to write a multilingual UI with useTranslation.
i18n and react-i18next
Internationalisation (i18n) prepares your app for multiple languages. The most common React library is react-i18next. The useTranslation hook returns a t function; t('hello') returns the string for the active language.
Translation files are kept as JSON. Switch languages with i18n.changeLanguage('en'); components re-render automatically.
For dates, numbers and currency use the Intl API; do not roll your own formatting.
Plurals and variables
i18next handles plural forms automatically: t('apple', { count: 3 }) returns the plural key. Variable interpolation uses the {{ name }} syntax.
If a key is missing the fallback language is used. This keeps the app working while new translations arrive.
Localise dates with Intl.DateTimeFormat and currency with Intl.NumberFormat.
Practice Write the Greeting component
Write a Greeting component. Get t from useTranslation and return <h1>{t('hello', { name: 'Alex' })}</h1>. Export it.
Starter code
import { useTranslation } from 'react-i18next';
// Write the Greeting component hereSample solution
import { useTranslation } from 'react-i18next';
function Greeting() {
const { t } = useTranslation();
return <h1>{t('hello', { name: 'Alex' })}</h1>;
}
export default Greeting;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match i18n concepts
| Term | Meaning |
|---|---|
useTranslation |
Gives the t function |
changeLanguage |
Switches language |
Intl |
Formats dates and numbers |
fallback |
Covers missing keys |
2 What does i18next do for a missing key?
- The app crashes
- It returns an empty string silently
- It returns the fallback language value Correct answer
- It auto-adds the key to the file
Explanation: The fallback language is used.
3 Fill in the blank: format a number as currency
const price = new Intl.NumberFormat('en', { style: '____', currency: 'USD' }).format(120);
const price = new Intl.NumberFormat('en', { style: 'currency', currency: 'USD' }).format(120);
Explanation: style: 'currency' for money.