Sub topic 3
Detecting and Switching the Locale at Runtime
Assumes working knowledge of React hooks, TypeScript, react-i18next, and async/await. A locale combines language and regional conventions, such as en-US or de-DE. Your app should detect a preferred locale, choose a supported fallback, and let the user change it.
Detecting and switching the locale
Check an explicit user choice first, then a URL or browser preference. Never activate an unsupported locale.
const supported = ['en', 'de'] as const;
function chooseLocale(requested: string | undefined) {
const language = requested?.split('-')[0];
return supported.includes(language as (typeof supported)[number])
? language
: 'en';
}
async function switchLocale(code: string, i18n: { changeLanguage: (c: string) => Promise<unknown> }) {
const locale = chooseLocale(code);
await i18n.changeLanguage(locale);
}A language switcher should use a native <select> or accessible buttons. Persist the choice only after validating it.
Keeping `html` attributes in sync
After switching, update the document language and direction. Screen readers use lang, while dir controls text flow.
await i18n.changeLanguage(code);
document.documentElement.lang = code;
document.documentElement.dir = i18n.dir(code);Embedded links and emphasis
Do not concatenate translated fragments. Word order differs between languages. Use named components with Trans, allowing translators to move the link or emphasis.
<Trans
i18nKey="terms"
values={{ name }}
components={{ link: <a href="/terms" />, bold: <strong /> }}
/>Right-to-left layout
Use CSS logical properties instead of left and right properties.
.card {
margin-inline-start: 1rem;
padding-inline: 1rem;
border-inline-start: 4px solid currentColor;
text-align: start;
}Loading catalogs on demand
Keep the initial bundle small by dynamically importing a catalog when needed.
if (!i18n.hasResourceBundle(code, 'translation')) {
const module = await import(`./locales/${code}.json`);
i18n.addResourceBundle(code, 'translation', module.default);
}
await i18n.changeLanguage(code);Keys, checks, and tests
Use stable semantic keys such as cart.items, not English sentences. Enable missing-key logging in development, extract keys in CI, and fail checks for missing translations.
Render components in tests with a chosen locale. Assert visible translated text, plural output, and lang or dir changes. For locale-aware behavior, test at least one right-to-left locale.
URLs and server rendering
Put the locale in the URL, such as /de/account, when links, sharing, SEO, or server rendering matter. The server should read that locale, load the same catalog, and render the initial HTML with matching translations. This prevents hydration mismatches before the client starts.
Exercise
Why should a locale be chosen and its catalog loaded before server-rendering the page?
Show answer
The server and client must start with the same language and messages, or the client may replace the HTML and cause a hydration mismatch.