Complex Translations Using the Trans Component

Learn how to interpolate or translate complex React elements.

In a few cases, it might be necessary to use a React component in the translations. For example, we might want to use the Link component from React Router to link to a different URL within a translation. The t() function does not support this out of the box. The solution to this problem comes in the form of the Trans component from react-18next. It is not always easy to understand how it should be used, but it can be a powerful tool.

Using the Link component inside translations

Let’s assume that we want to use a Link component inside of our translations. The code might resemble this:

    <input type="checkbox" name="terms" />
    Ich akzeptiere die <Link to="/terms">AGB</Link>

Using the Link component in such a translation would not work. Translations are strings, and would not be able to define that the <Link> component refers to the Link component from the React Router package.

The Trans component offers the solution to our problem. Translations using this component can include numbered placeholders. These placeholders will later be replaced with components that will appear in the same place as they are used as in the Trans component.

Let’s look at the above example using the Trans component:

// Translations:
const de = {
  terms: 'Ich akzeptiere die <1>AGB</1>.',

const en = {
  terms: 'I accept the <1>Terms and Conditions</1>.',

// JSX:
    <input type="checkbox" />
    <Trans i18nKey="terms">
      I accept the <Link to="/terms">Terms and Conditions</Link>.

Our text is wrapped by a Trans element. The text itself is only a placeholder that is used if the i18nKey prop does not contain a value that corresponds to a translation.

Let’s look at the numbering now. Which specific text is placed and where it is placed is decided by the index value of the child element, similar to React.createElement().

Using the above example, we have the following counting result:

0: I accept the
1: <Link to="/terms">Terms and Conditions</Link>
2: .

The <1>Terms and Conditions</1> will be replaced by the <Link> element because it corresponds to the index value of 1 in the array of children. Let’s see this interactively:

Get hands-on with 1200+ tech skills courses.