React i18n break lines in JSON String

for example you write below text in JSON language file.

text:"Hello \n How are you? \n what are you doing?"

and then in return part write

<div id='app'><div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<script>
      render() {
          return (
              text.split('\n').map(c => {
                  return ( <p> {c} </p>) 
                   });
                 )
               }
              

              ReactDOM.render(
                <BreakLine / >
                document.getElementById('app')
              )
</script>

well, when call split method, try to create list and seperate from '\n' and with method map type each of them on paragraph so can break line ;))


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"
        // ----------------^ new line char
      }
    }
  }
}, 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>

You also can do it with CSS that's very easy to do:

CSS:

#root {
  white-space: pre-line;
}

HTML:

<script src="https://unpkg.com/[email protected]/dist/umd/i18next.min.js"></script>

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

It will interpret the \n in the translation JSON as a linebreak!!!


<br /> is the correct way, but it does not goes into the text or translations. Example :

<div>
  {'my text line 1'}
  <br />
  {'my text line 2'}
</div>

However, if you want to keep the line breaks (\n) inside the text, then do it like this using dangerouslySetInnerHTML :

const text = "This is a line. \n This is another line. \n Yet another line";
<div dangerouslySetInnerHTML={text} />