乐闻世界logo
搜索文章和话题

How to use html tags with react-i18next locales?

1个答案

1

When using the react-i18next library for internationalization, embedding HTML tags within translated text is often necessary for formatting purposes. For instance, you may need to emphasize specific words within a text segment or add links. react-i18next provides several methods to achieve this while ensuring both internationalization and safe HTML rendering.

Method 1: Using the Trans Component

The Trans component is a key tool provided by react-i18next for handling complex translation scenarios, such as inserting HTML tags or components. When using this component, you can directly include HTML tags in your translation resource files.

Consider the following translation resources:

json
{ "welcome": "<strong>Welcome</strong> to our website, <a href='/about'>learn more</a> about us." }

In your React component, use it as follows:

jsx
import React from 'react'; import { Trans, useTranslation } from 'react-i18next'; function MyApp() { const { t } = useTranslation(); return ( <div> <Trans i18nKey="welcome"> <strong>Welcome</strong> to our website, <a href="/about">learn more</a> about us. </Trans> </div> ); } export default MyApp;

In this example, the Trans component safely renders HTML while preserving the structure of the translated text.

Method 2: Using dangerouslySetInnerHTML

If you prefer not to use the Trans component, another option is to leverage React's dangerouslySetInnerHTML attribute. However, this method should be used with caution, as it may introduce XSS (Cross-Site Scripting) security vulnerabilities.

First, ensure your translation strings are secure, then implement it as follows:

jsx
import React from 'react'; import { useTranslation } from 'react-i18next'; function MyApp() { const { t } = useTranslation(); return ( <div> <p dangerouslySetInnerHTML={{ __html: t('welcome') }}></p> </div> ); } export default MyApp;

Security Considerations

  • When using dangerouslySetInnerHTML, ensure translation strings are sourced securely to prevent XSS attacks.
  • Prefer using the Trans component, as it offers a safer and more flexible approach for handling HTML and components.

By employing these methods, you can effectively incorporate HTML tags within react-i18next while maintaining robust internationalization and multilingual support.

2024年8月8日 16:21 回复

你的答案