Sub topic 11
Embedding links and emphasis in translated messages
This chapter covers messages that contain markup, such as a link or a bold word in the middle of a sentence. It assumes you have react-i18next set up, know useTranslation and t, and can use interpolation ({{name}}). It also assumes you are comfortable with React elements and props.
The problem with splitting sentences
Take this English sentence: "I accept the terms of service, Ada." The words "terms of service" are a link, and the name is bold. A first attempt often splits the sentence into pieces:
import { useTranslation } from 'react-i18next';
export function BadTerms({ name }: { name: string }) {
const { t } = useTranslation();
return (
<p>
{t('terms.before')} <a href="/terms">{t('terms.link')}</a>, <strong>{name}</strong>.
</p>
);
}This breaks in translation for three reasons.
- Word order differs. A language may put the link first, or the name before the verb. The code fixes the order, so the translator cannot change it.
- Fragments lose context. A translator sees "I accept the" and "terms of service" as separate rows. Grammar such as case endings or gender agreement may depend on the whole sentence.
- Punctuation is in the code. The comma and the full stop belong to the sentence, but here they live in JSX. Some languages use different punctuation.
This is the same mistake as string concatenation with variables, which an earlier chapter covered. The fix is also similar: keep the whole sentence as one message and mark where the elements go.
Tagged messages with Trans
react-i18next provides the Trans component for this. The catalog entry holds the whole sentence, with named tags around the parts that need markup:
{
"terms": "I accept the <link>terms of service</link>, <bold>{{name}}</bold>."
}The component maps each tag name to a React element:
import { Trans } from 'react-i18next';
// catalog entry: "terms": "I accept the <link>terms of service</link>, <bold>{{name}}</bold>."
export function Terms({ name }: { name: string }) {
return (
<Trans
i18nKey="terms"
values={{ name }}
components={{ link: <a href="/terms" />, bold: <strong /> }}
/>
);
}How it works:
Translooks uptermsin the active language, astdoes.- It fills in
{{name}}fromvalues. - It parses the tags in the result. For each tag name it finds in
components, it clones that element and puts the tagged text inside as its children.
The <a href="/terms" /> element has no children in your code. The text between <link> and </link> becomes its content. A German translator can now write this, and no code changes:
{
"terms": "Ich akzeptiere die <link>Nutzungsbedingungen</link>, <bold>{{name}}</bold>."
}A translator who needs a different order can move the tags freely, as long as every tag is opened and closed.
Choosing between named tags and indexed tags
The example above uses an object for components, so tags have names (<link>). Trans also accepts an array, and then tags use numbers such as <0>terms of service</0>.
| Style | Catalog text | `components` prop | Trade-off |
|---|---|---|---|
| Named | `<link>terms</link>` | `{ link: <a href="/terms" /> }` | Readable for translators. Reordering is safe. |
| Indexed | `<0>terms</0>` | `[<a href="/terms" />]` | Shorter, but the numbers mean nothing to a translator. |
Prefer named tags. A translator can guess that <bold> means emphasis, but not what <1> means. Use clear, stable names, and reuse the same name for the same purpose across messages.
Values go through values, not through JSX
Variables inside a tagged message still use {{name}} and are supplied through values. Do not place a variable as a JSX child of Trans for this purpose. Children are an older way to write the default message in code. They work, but the catalog and the code can then drift apart, and key extraction tools have to guess. Pass i18nKey, values and components, and keep the text in the catalog.
If the message also has a plural, pass count:
import { Trans } from 'react-i18next';
export function Unread({ count }: { count: number }) {
return (
<Trans
i18nKey="unread"
count={count}
values={{ count }}
components={{ bold: <strong />, inbox: <a href="/inbox" /> }}
/>
);
}with these catalog entries:
{
"unread_one": "You have <bold>{{count}}</bold> unread message in your <inbox>inbox</inbox>.",
"unread_other": "You have <bold>{{count}}</bold> unread messages in your <inbox>inbox</inbox>."
}The plural suffixes work the same way as with t. Each form is a full sentence with its own tags.
Escaping and safety
The Trans component does not render the catalog string as HTML. It parses only the tags you listed, and it builds React elements from your components map. Text between tags goes through React's normal escaping. This is why the setup chapter could set escapeValue: false safely.
Some details to keep in mind:
- Unknown tags. A tag in the message with no matching entry in
componentsis not turned into an element. Its content may show as plain text or as literal tag text, depending on yourtransKeepBasicHtmlNodesForoption. Test this with a deliberately broken message. - Basic HTML nodes. By default, react-i18next keeps simple tags such as
<br>,<strong>,<i>and<p>in a message and renders them as elements, even if you did not list them incomponents. This is convenient, but it lets translators add markup. Narrow it withreact: { transKeepBasicHtmlNodesFor: [] }ininitif you want only listed tags to render. - Attributes in the message. Keep attributes such as
hrefin your code, not in the catalog. If a URL is in the catalog, a translator can change it by accident, and a malicious string could point somewhere unsafe. Thecomponentsentry controls where the link goes. - Localised URLs. If the target page differs by language, build the URL in code from the active locale, and pass it to the element:
link: <a href={/${i18n.language}/terms} />.
Attributes and accessibility
Markup in a message is not limited to visible text. A link needs an accessible name, and that name comes from the translated text between the tags. Because the text is translated, screen reader users hear it in their own language.
Two cases need extra care.
- Link text must make sense alone. "Click <link>here</link>" is poor in any language. Write "Read the <link>terms of service</link>" so the link text describes the target.
- Attributes that hold text. An
aria-labelortitleon the element incomponentsis not translated byTrans. Translate it withtand pass it in:link: <a href="/terms" aria-label={t('terms.linkLabel')} />.
Emphasis has a similar limit. <strong> signals importance to assistive technology, while <em> signals stress. Choose the element for its meaning, not just its look, and let CSS handle appearance.
Common errors
- Unbalanced tags.
<link>termswithout a closing tag, or tags that overlap, give broken output. Ask translators to keep tags paired, and check this in review or in a test. - Renamed tags. A translator who changes
<bold>to<b>breaks the mapping. Tell them tag names must stay as they are. A translation tool that marks tags as protected placeholders helps. - Dropped tags. If a translation omits
<link>, the link disappears. Compare the set of tags in each language against the source. - Whitespace around tags. Spaces next to a tag matter.
<bold> {{name}} </bold>renders spaces inside the bold element. Keep tags tight around their text. - Nested components. Tags can nest, for example
<link><bold>terms</bold></link>, andTranswill nest the elements. A component that needs its own children from code, such as an icon, is better placed outside the message. - Using
Transwheretis enough. A plain message with only variables needs no markup. Uset, which is simpler and cheaper.
A quick test catches several of these problems. It renders the component and checks the structure:
import { render, screen } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
import { Terms } from './Terms';
test('renders the link inside the translated sentence', async () => {
await i18n.changeLanguage('de');
render(
<I18nextProvider i18n={i18n}>
<Terms name="Ada" />
</I18nextProvider>
);
const link = screen.getByRole('link', { name: 'Nutzungsbedingungen' });
expect(link).toHaveAttribute('href', '/terms');
});This test finds the link by its translated accessible name and checks the href that the code controls.
Summary of decisions
- Keep one full sentence per message. Mark parts with named tags.
- Put elements and URLs in
components, and text and tags in the catalog. - Use
valuesfor variables andcountfor plurals. - Use
twhen no markup is needed. - Limit which tags can render, and review tag sets across languages.
Exercise
A catalog entry reads "Read our <0>privacy policy</0> or <1>contact us</1>." Rewrite it so a translator can understand and safely reorder it, and write the matching Trans call. Where should the href values live, and why?
Show answer
Use named tags: "Read our <policy>privacy policy</policy> or <contact>contact us</contact>." The call is <Trans i18nKey="help" components={{ policy: <a href="/privacy" />, contact: <a href="/contact" /> }} />. The href values stay in the components map in code, not in the catalog. That way translators cannot change or break a URL, no unsafe link can enter through a translation file, and the translator can still move the tags to fit the grammar of their language.
Exercise
A German translation of the "terms" message omits the <bold> tags around {{name}}. What happens when the component renders, and how would you catch this before release?
Show answer
The name still appears, because interpolation is independent of the tags, but it renders as plain text without the strong element. Nothing throws, so the error is silent. Catch it with a check that compares the set of tags in each language entry against the source entry (in a script or unit test), or with a component test that asserts the strong element exists under each supported locale.