React i18n break lines in JSON String

Nocebo picture Nocebo · Aug 24, 2017 · Viewed 16.4k times · Source

I'm working with i18next for react https://github.com/i18next/react-i18next. I'm struggling to break lines within the string in my JSON language file.

This is what I already tried, which doesn't break a new line:

  • line: "This is a line. \n This is another line. \n Yet another line", enter image description here
  • line: ("This is a line."+ <br/> + "This is another line. \n Yet another line"), enter image description here
  • line: ('This is a line. <br/> This is another line. \n Yet another line'), enter image description here

I obviously try to make a new line after each sentence. This is how I call it:

<TooltipLink onClick={() => {
    this.toggleHelpTextDialog(t('test:test.line'));
}}/>

Any ideas? Thanks!

Answer

felixmosh picture felixmosh · Feb 18, 2019

You can do it with css white-space: pre-line; & \n in the translation text.

const root = document.getElementById('root');

i18next.init({
  lng: 'en',
  resources: {
    en: {
      translation: {
        "key": "Hello world\nThis sentence should appear on the second line"
      }
    }
  }
}, function(err, t) {
  // initialized and ready to go!
  root.innerHTML = i18next.t('key');
});
#root {
  white-space: pre-line;
}
<script src="https://unpkg.com/[email protected]/dist/umd/i18next.min.js"></script>

<div id="root"></div>