React-i18next: Unexpected format output

Created on 4 Mar 2017  路  3Comments  路  Source: i18next/react-i18next

I try to format date, but result that i get on the page looks like:

output on the page

screen shot 2017-03-04 at 13 18 27
Looks like encoding problem, but i have UTF-8 charset in my index.html.
I found that problem occurs with following characters: /'><

Where can be the problem?

i18n.js

...
import moment from 'moment';

function loadLocales(url, options, callback) {
  try {
    const waitForLocale = require(`bundle-loader!../locales/${url}.json`);
    waitForLocale((locale) => {
      callback(locale, { status: '200' });
    });
  } catch (e) {
    callback(null, { status: '404' });
  }
}

i18next
  .use(XHR)
  .use(Cache)
  .init({
    lng: 'de',
    fallbackLng: false,
    debug: true,
    ns: ['translation'],
    defaultNS: 'translation',
    interpolation: {
      format: (value, format) => {
        if (value instanceof Date) return moment(value).format(format);
        return value;
      },
    },
    backend: {
      loadPath: '{{lng}}/{{ns}}',
      parse: data => data,
      ajax: loadLocales,
    }
  });

locales/de/translation.json

{
 "key1": "value of key 1 in de",
 "key2": "value of key 2 in de",
 "test": "tetetet {{date, DD/MM/YY}}"
}

in the component i use it like:

<h2 className={theme.grid}>{t('test', { date: new Date() })}</h2>

Most helpful comment

i18next does for security reason encode interpolated stuff...to avoid xss attacks (that's great eg. for jquery and other frameworks)

React itself does encode content itself (only option to not encode is dangerouslysetinnerhtml) so if i18next encodes and react we end in double encoding -> so turning it off in i18next fixes it by still secure as react take care of that.

All 3 comments

you will need to set escaping to false like here: https://github.com/i18next/react-i18next/blob/master/example/app/i18n.js#L25

please let me know if this solves your issue?

@jamuhl yes, this works perfectly. Thank you for quick answer. Could you explain more about comment near this option (not needed for react!!)? it's confusing me a bit

i18next does for security reason encode interpolated stuff...to avoid xss attacks (that's great eg. for jquery and other frameworks)

React itself does encode content itself (only option to not encode is dangerouslysetinnerhtml) so if i18next encodes and react we end in double encoding -> so turning it off in i18next fixes it by still secure as react take care of that.

Was this page helpful?
0 / 5 - 0 ratings