Using the Trans Component from react-i18next

September 19, 2024

Internationalization (i18n) is a crucial aspect of modern web applications, allowing you to cater to a global audience by supporting multiple languages. The react-i18next library is a popular choice for handling i18n in React applications. One of its powerful features is the Trans component, which allows you to include dynamic content and HTML elements within your translations. In this article, we'll explore how to use the Trans component effectively with a practical example.

Let's consider a component where we need to include links to the terms of service and privacy policy within a translated string. Here's how you can achieve this using the Trans component from react-i18next.

1. Setting Up Translations

First, we need to define our translations. In this example, we'll use an English translation file that includes a key for the agreement text.

index.ts
export default {
agree:
'I agree to the <termsLink>terms of service</termsLink> and <privacyLink>privacy policy</privacyLink>',
}

We define a key agree with the value containing placeholders for termsLink and privacyLink. These placeholders will be replaced by the actual HTML elements when rendered.

2. Using the Trans Component in the Page

Next, we'll use the Trans component in our component to render the translated string with embedded links.

index.tsx
import React from 'react'
import { Trans, useTranslation } from 'react-i18next'
export default function Page() {
const { t } = useTranslation() // Hook to access translation function
return (
<main>
<label htmlFor="agree">
<Trans
i18nKey="agree" // Key in the translation file
components={{
termsLink: <a href="/terms" />, // Component to replace <termsLink>
privacyLink: <a href="/privacy" />, // Component to replace <privacyLink>
}}
/>
</label>
<input type="checkbox" id="agree" name="agree" />
</main>
)
}

Conclusion

The Trans component from react-i18next is a powerful tool for handling complex translations that include dynamic content. By following the steps outlined in this article, you can effectively use the Trans component to enhance the internationalization of your React applications. For more information and advanced usage, refer to the react-i18next documentation.

Share this post on Twitter