Sub topic 5
Translating Text in Components
This chapter covers how components read translated text with useTranslation. It assumes you can write React function components and hooks, and that you have the react-i18next setup from the previous chapter: an i18n.ts file with two catalogs, English as the fallback, and initReactI18next registered. It does not cover plurals, Intl formatting, or rich markup. Later chapters handle those.
The working model
A translation key is a stable string such as greeting. A message catalog maps each key to a message in one language. The t function takes a key, looks it up in the active language, and returns the message. If the key is missing there, t tries the fallback language. If it is missing everywhere, t returns the key itself.
The useTranslation hook gives a component access to t and to the i18n instance. It also subscribes the component to language changes, so calling i18n.changeLanguage re-renders every component that uses the hook.
Using useTranslation
Replace each hard-coded string with a call to t. This is the component from the setup chapter's catalog:
import { useTranslation } from 'react-i18next';
export function Welcome({ name }: { name: string }) {
const { t } = useTranslation();
return <h1>{t('greeting', { name })}</h1>;
}With lng: 'en', the heading renders Hello, Ada! for name="Ada". After i18n.changeLanguage('de'), it renders Hallo, Ada! without any change to the component.
Two points to keep in mind:
- The second argument to
tis an options object. Its properties fill{{placeholders}}in the message. Passing{ name }is shorthand for{ name: name }. treturns a string. You can use it in any place that accepts a string, including attributes.
import { useTranslation } from 'react-i18next';
export function SearchBox() {
const { t } = useTranslation();
return (
<input
type="search"
placeholder={t('search.placeholder')}
aria-label={t('search.label')}
/>
);
}Attributes such as placeholder, aria-label, alt, and title are user-facing text. They are easy to miss during a translation pass because they never appear as JSX children.
Namespaces and nested keys
The catalogs in the setup chapter put everything under a translation namespace. A namespace is a named group of messages inside a language. It is the first level under the language code, and translation is the default. Larger apps split catalogs by feature, for example common, cart, and account, and pass the namespace to the hook:
import { useTranslation } from 'react-i18next';
export function CartTitle() {
const { t } = useTranslation('cart');
return <h2>{t('title')}</h2>;
}You can also name a namespace inside the key with a colon separator: t('common:save'). With an array, useTranslation(['cart', 'common']), the first namespace is the default and the others need the prefix.
Keys can be nested objects. By default i18next uses . as the key separator, so t('search.placeholder') reads this catalog:
const en = {
translation: {
search: {
placeholder: 'Search products',
label: 'Search',
},
},
};A flat catalog with keys like 'search.placeholder' also works if you set keySeparator: false. Pick one style per project and keep to it.
Fallbacks and missing keys
Three situations produce different results:
| Situation | What `t` returns |
|---|---|
| Key exists in the active language | The active-language message |
| Key missing in the active language, present in `fallbackLng` | The fallback message |
| Key missing everywhere | The key string, for example `search.placeholder` |
A key string on screen is the visible sign of a missing translation. You can supply a default for a single call with defaultValue:
import { useTranslation } from 'react-i18next';
export function Banner() {
const { t } = useTranslation();
return <p>{t('banner.new', { defaultValue: 'New this week' })}</p>;
}Use defaultValue sparingly. A default written in code is a second copy of the English text, and it can drift from the catalog. Later chapters cover extraction tools and checks that catch missing keys without relying on defaults.
Using t outside of components
The hook only works inside React components and other hooks. Utility modules, validation functions, and error handlers have no component to call it from. Import the i18n instance and use its t method directly:
import i18n from './i18n';
export function validateEmail(value: string): string | null {
if (!value.includes('@')) {
return i18n.t('errors.emailInvalid');
}
return null;
}This works, but it captures the language at the moment of the call. If the user switches language later, a message you already stored in state stays in the old language. Prefer returning a key (or an error code) from such functions and calling t in the component that displays it:
import { useTranslation } from 'react-i18next';
export function EmailError({ errorKey }: { errorKey: string | null }) {
const { t } = useTranslation();
return errorKey ? <p role="alert">{t(errorKey)}</p> : null;
}Now the message is looked up on every render, so it follows the active language.
Common errors
Calling t at module level. This code runs once, at import time:
import i18n from './i18n';
// Wrong: evaluated once, never updates when the language changes.
const TITLE = i18n.t('cart.title');The constant keeps whatever language was active when the module loaded. Store the key in the constant and call t during render instead:
import { useTranslation } from 'react-i18next';
const TITLE_KEY = 'cart.title';
export function Title() {
const { t } = useTranslation();
return <h2>{t(TITLE_KEY)}</h2>;
}The same applies to arrays of menu items or table columns defined outside a component. Define the keys outside and translate them inside.
Building messages by concatenation. Code such as t('hello') + ', ' + name + '!' fixes the word order and punctuation to the source language. Other languages may need the name first or different punctuation. Put a placeholder in the message, as in Hello, {{name}}!, and let translators arrange it. The next chapter treats this in detail.
Using the English text as the key. Keys such as 'Add to cart' seem convenient, but any wording change to the English text changes the key and breaks every other catalog. Use identifiers that describe the role of the text, for example cart.addButton.
Forgetting the component is not subscribed. If you import i18n and call i18n.t inside a component instead of using the hook, the component does not re-render when the language changes. Use useTranslation inside components.
Rendering before resources are ready. With in-memory resources, as in the setup chapter, translations are available immediately. With a backend that loads files, t can run before the catalog arrives and return keys. By default useTranslation uses React Suspense, so wrap the tree in <Suspense> or pass { useSuspense: false } and check the ready flag:
import { useTranslation } from 'react-i18next';
export function Profile() {
const { t, ready } = useTranslation('account', { useSuspense: false });
if (!ready) return null;
return <h2>{t('profile.title')}</h2>;
}A short checklist for a translation pass
- Search the component for string literals in JSX children.
- Check attributes:
placeholder,aria-label,alt,title. - Check strings assembled in helper functions, such as button labels and error messages.
- Replace each string with a key, and add the message to every catalog.
- Switch the language in the running app and confirm that nothing remains in the old language.
Exercise
A developer writes const LABELS = [i18n.t('nav.home'), i18n.t('nav.about')]; at the top of a module and renders LABELS in a component. Users who switch from English to German still see English navigation labels. Why does this happen, and how would you fix it?
Show answer
The i18n.t calls run once, when the module is imported, so the array holds the strings for whichever language was active then. Later calls to changeLanguage do not rerun them. Store the keys instead (const LABEL_KEYS = ['nav.home', 'nav.about'];) and call t(key) inside the component, where useTranslation re-renders it on language change.
Exercise
What does t('cart.checkout') return when cart.checkout exists in neither the active language nor the fallback language? What is the practical use of this behaviour?
Show answer
It returns the key string, cart.checkout. Seeing a raw key in the UI is a visible signal that a translation is missing, which makes gaps easy to spot during manual testing.