Search code examples
reactjsi18next

i18next react - HTML tags


I'm doing the translation of a react project, so I'm using i18next.

So far I haven't had any problems, following the doc everything works, only I'm getting to a little more difficult subject, I'd like to have html code (very simple) in my translation, for the layout.

Only, the
tags are displayed as text, and are not taken into account in html, something I don't understand, if I read the doc well, they should be...

Do you have a solution ?

Here is my i18n.js config:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

import translation from "./translation.json"
// not like to use this?
// have a look at the Quick start guide 
// for passing in lng and translations on init

const resources = translation

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    fallbackLng: 'en',
    debug: true,

    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    react:{
      bindI18n: 'languageChanged',
      transSupportBasicHtmlNodes: true,
      transKeepBasicHtmlNodesFor: ['br', 'strong', 'i'],
      useSuspense: false //   <---- this will do the magic
    }
  });


export default i18n;

The translation (it's a test!) :

"home_text":"hello <br/> world"

Here I call the translation :

<p style={{color:'#A1A1A1', fontWeight:'400'}}>
    {t('home_text')}
</p>

I probably did the configuration wrong, but I don't see where...


Solution

  • In order to render html elements out of translations you will need to use Trans component which allows you to mix & match html elements and React components.

    // usage 
    <Trans i18nKey="home_text" components={[<br />]} />
    
    // translation.json
    {
      "home_text": "hello <1/> world"
    }
    

    Starting i18next-react v11.6.0 there is an alternative way to declare components.

    // usage 
    <Trans i18nKey="home_text" components={{newLine: <br />}} />
    
    // translation.json
    {
      "home_text": "hello <newLine/> world"
    }
    

    A personal recommendation, for line break use the \n inside your translations with a combination of css.

    For an example you can check this answer: React i18n break lines in JSON String