Sub topic 10
Keeping html lang and dir in sync
This chapter covers the two attributes on the <html> element that tell browsers and assistive technology which language and text direction the page uses. It assumes you can write React function components and hooks, have react-i18next set up as in the earlier chapters, and know basic HTML and CSS. You should already know how i18n.changeLanguage works.
Why the attributes matter
Translating the text in your components is not enough. The document itself must say what language it is in. Two attributes on <html> do this:
langholds a BCP 47 language tag such asen,deorar.dirholds the base text direction:ltr(left to right),rtl(right to left) orauto.
If these stay at their initial values after the user switches language, several things go wrong:
| Consumer | What it does with the attribute | What breaks when it is stale |
|---|---|---|
| Screen readers | Pick a speech synthesizer voice and pronunciation rules from `lang` | German text is read with English pronunciation |
| Browser translation | Decides whether to offer to translate the page | The browser offers to translate a page that is already in the user's language |
| Hyphenation and quotes | CSS `hyphens: auto` and `<q>` quote marks follow `lang` | Wrong hyphenation rules and quote characters |
| Font selection | Browsers choose language-specific glyph variants, for example for Chinese, Japanese and Korean (CJK) text | Wrong glyph shapes for shared Han characters |
| Layout | `dir` sets the base direction for text and for logical CSS properties | Arabic text is laid out as left to right |
| Spell checkers | Use `lang` to choose a dictionary in editable fields | Valid words are flagged as errors |
The static index.html of a Vite or webpack app usually ships with <html lang="en">. That value is correct only for the first render in English. Your code has to update it at runtime.
Where the values come from
You already have a language code in i18next. The direction comes from i18n.dir(code), which returns 'ltr' or 'rtl' based on a built-in list of right-to-left languages. If you omit the code, it uses the current language.
import i18n from './i18n';
console.log(i18n.dir('en')); // 'ltr'
console.log(i18n.dir('ar')); // 'rtl'
console.log(i18n.dir('he')); // 'rtl'
console.log(i18n.dir('fa')); // 'rtl'Prefer i18n.dir over a hand-written list of codes. It is simple to maintain and it handles tags with regions, such as ar-EG, because it works from the language subtag.
The approach from the previous chapter
The language switcher in the earlier chapter updates the attributes inside its own change handler:
import { useTranslation } from 'react-i18next';
const LANGUAGES = [
{ code: 'en', label: 'English' },
{ code: 'de', label: 'Deutsch' },
];
export function LanguageSwitcher() {
const { i18n } = useTranslation();
async function change(code: string) {
await i18n.changeLanguage(code);
document.documentElement.lang = code;
document.documentElement.dir = i18n.dir(code);
}
return (
<select value={i18n.resolvedLanguage} onChange={(e) => change(e.target.value)}>
{LANGUAGES.map((l) => (
<option key={l.code} value={l.code}>{l.label}</option>
))}
</select>
);
}Note the order. The handler awaits changeLanguage first, so the catalog is ready, and then writes the attributes. This works while the switcher is the only way the language changes. It has a weakness: the attributes are tied to one UI control, so any other path that changes the language leaves them stale.
Where the handler approach fails
Language can change without the switcher being involved:
- The initial language is detected from the browser,
localStorageor the URL when the app starts. No change handler runs, solangstays at the value inindex.html. - A route change selects a locale from the URL, such as
/de/cart. - A test or another component calls
i18n.changeLanguagedirectly. - The user's saved profile loads after the first render and sets a different language.
In each case the text is translated but <html lang> is wrong. The fix is to attach the update to the i18n instance, not to a UI control.
Synchronising from i18next events
i18next emits a languageChanged event each time the active language changes, and it also fires after initialisation resolves the starting language. Subscribing to this event gives one place that keeps the attributes correct, whatever triggered the change.
import i18n from './i18n';
function syncDocument(lng: string) {
const root = document.documentElement;
root.lang = lng;
root.dir = i18n.dir(lng);
}
i18n.on('languageChanged', syncDocument);
// Cover the case where initialisation finished before this module ran.
if (i18n.isInitialized) {
syncDocument(i18n.resolvedLanguage ?? i18n.language);
}The last block matters. languageChanged fires during init. If you register the listener after init has already finished, you miss that first event, so you set the starting values yourself. Checking isInitialized handles both orders of loading.
Put this code in the same module that configures i18next, or in a module imported once at startup. Do not register it inside a component body. A listener added on every render accumulates and leaks.
Doing it in a React effect
If you prefer to keep the logic inside React, a hook with useEffect does the same job. Because useTranslation re-renders the component when the language changes, the effect runs again with the new value.
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
export function useDocumentLanguage() {
const { i18n } = useTranslation();
const lng = i18n.resolvedLanguage ?? i18n.language;
useEffect(() => {
document.documentElement.lang = lng;
document.documentElement.dir = i18n.dir(lng);
}, [lng, i18n]);
}Call useDocumentLanguage() once, in your root App component. Calling it in several components is harmless but redundant.
The two approaches compare like this:
| Concern | `languageChanged` listener | `useEffect` hook |
|---|---|---|
| Runs without React mounted | Yes | No |
| Runs before first paint | Yes, if registered before render | No, effects run after paint |
| Cleanup | You must call `i18n.off` if the module can reload | Handled by React |
| Fits server rendering | No `document` on the server, so it must be guarded | Effects do not run on the server |
For a client-only app, the event listener is the better default because it sets the attributes before React paints. With server rendering you also write the attributes into the HTML the server sends. The last chapter of this tutorial covers that.
Language versus resolved language
i18next has two related properties, and they differ when a fallback applies.
i18n.languageis the language that was requested or detected, for examplede-AT.i18n.resolvedLanguageis the language whose catalog is actually in use, for exampledeif you only shipde.
The page content is in the resolved language, so lang should describe what the user reads. If you set lang="de-AT" but show English because no German catalog exists, a screen reader would use a German voice for English words. Use resolvedLanguage when it is defined, and fall back to language otherwise. The sketches above do this with ??.
Resolved language can be undefined before the first catalog loads, which is why the fallback expression is needed.
Marking up passages in another language
The lang on <html> describes the page as a whole. When a passage differs from the page language, set lang on that element. This is common for product names, quotations and language names in a switcher.
export function LanguageOption({ code, label }: { code: string; label: string }) {
return <option value={code} lang={code}>{label}</option>;
}Without the per-option lang, a screen reader on an English page reads "Deutsch" with English pronunciation. Setting lang on the option fixes that. Labels in a language switcher should always be written in their own language, so users who cannot read the current language can still find theirs.
Direction beyond the root element
dir on <html> sets the base direction for the whole document. A few cases need more care:
- Text from users or an external source may be in a different direction from the page. Use
dir="auto"on the element that shows it, so the browser infers the direction from the first strong character. - Numbers, Latin brand names and URLs inside right-to-left text are handled by the Unicode bidirectional algorithm. Punctuation at the edges of such fragments can move to the wrong side. Wrapping the fragment in
<bdi>isolates it. - The attribute value is
rtlorltr, neverrightorleft. An invalid value is ignored and the document keeps its default direction.
The CSS side of right-to-left support, including logical properties, is in a later chapter. Here the point is that those properties read dir from the document, so the attribute must be correct first.
Common errors
- Setting the attributes before the language changes. Writing them before
await i18n.changeLanguage(code)completes causes a flash in which the old text is shown with the new direction. Update after the change resolves, or use the event. - Registering the listener inside a component. Each render adds another listener. Register once at module level.
- Missing the initial language. A listener alone leaves
langat theindex.htmlvalue ifinitfinished earlier. Apply the starting values explicitly. - Using
i18n.languagewith a missing region catalog. The attribute then names a language the user is not reading. PreferresolvedLanguage. - Hard-coding a list of right-to-left codes. The list drifts out of date and misses regional tags. Use
i18n.dir. - Forgetting the static value. Set the
langinindex.htmlto your default language so the page is correct before JavaScript runs.
Checking the result
Open the browser developer tools and inspect the <html> element while you switch languages. You should see lang and dir change with each switch. To check from a unit test, assert on document.documentElement:
import { expect, test } from 'vitest';
import i18n from './i18n';
import './syncDocument';
test('html attributes follow the language', async () => {
await i18n.changeLanguage('de');
expect(document.documentElement.lang).toBe('de');
expect(document.documentElement.dir).toBe('ltr');
});This test assumes the listener lives in syncDocument.ts and the Vitest environment is jsdom or happy-dom, so that document exists.
Exercise
A user opens your app with a browser set to Arabic. The detector picks ar during init, and no one touches the language switcher. The text appears in Arabic but flows left to right, and a screen reader uses an English voice. Which approach would cause this, and what is the smallest change that fixes it?
Show answer
The attributes are written only in the switcher's change handler, which never runs for the detected language, so lang and dir keep the values from index.html. Move the update into a languageChanged listener on the i18n instance, registered once at module level, and also apply the starting values when i18n.isInitialized is already true. Use i18n.dir(lng) for the direction and resolvedLanguage for lang.
Exercise
Your app ships only a de catalog, and a user's browser requests de-AT. Which value should go in <html lang>, and why?
Show answer
Use i18n.resolvedLanguage, which is de, because that is the language the user actually reads. Setting de-AT would be acceptable only if the catalog really contained Austrian German. Setting a language that does not match the visible text misleads screen readers and browser translation.