HTML tags in i18next translation files in React

Petr Gazarov picture Petr Gazarov · Oct 3, 2016 · Viewed 14.2k times · Source

I'm using i18next in a project and can't get around including html tags in translation files and having them properly rendered.

An example of my .json translation file:

"en": {
  "product": {
    "header": "Welcome, <strong>User!</strong>"
  }
}

There is an excellent answer to this question, but relating to JQuery. I'm not using JQuery, my project is React and here is the setup that I have:

import i18next from 'i18next';
import en from 'locales/en';

i18next.
  init({
    lng: 'en',
    fallbackLng: false,
    resources: en,
    debug: false,

    interpolation: {
      escapeValue: false
    }
  });

export default i18next.t.bind(i18next);

In component I have:

import t from 'i18n';

t('product.header')

Html that I want:

Welcome, <strong>User!</strong>

Html I'm getting:

Welcome, &lt;strong&gt;User!&lt;/strong&gt

Thanks

Answer

jamuhl picture jamuhl · Oct 18, 2016

not a problem of react-i18next - you just can't add html into a react element. react will safe you from xss vulnerability and escape the content:

more detail and possible solution: https://facebook.github.io/react/tips/dangerously-set-inner-html.html

but be aware if you put user content there not escaped you open your site to xss attacks.

more secure reading the react-i18next readme: https://github.com/i18next/react-i18next#interpolate-component

which makes you split content

so the "best" solution - at least what we do - is using markdown in the translations and use eg: https://github.com/acdlite/react-remarkable to convert that to formatted content.