7

I am having some dynamic JSON strings like below:

Status is unknown\nThe combination is excluded by the following restriction\nRestriction number 2. 01 Mar 12 08:03:01 0--Exclusion--OrderDeliveryTimeframe.equals(\"oneMonth\") && OrderShipping.equals(\"air\")\n\n

So when I am printing the same as output, \n is not rendering the text in new line. So I wrote the below code:

return <div>
  {item.intro.replace(/[\n \n\n]/g, "\n")}
     <br/>

Now the problem is - It is rendering the text in next line after encountering first occurrence of\n, but not after that. Neither it is working for \n\n. I think I am missing something. Can someone please help me with this. Thanks in advance.

norbitrial
  • 14,716
  • 7
  • 32
  • 59
  • Does this answer your question? [Line break in HTML with '\n'](https://stackoverflow.com/questions/39325414/line-break-in-html-with-n) – mickmackusa Jul 11 '22 at 01:38

4 Answers4

14

\n isn't a newline in HTML, it's just a space. Any series of whitespace characters in HTML is treated as one space.

The React part of this is how you use br elements to do what you want to do.

The easiest way is to tell the div to treat whitespace different, as discussed in this question's answers.

return <div style={{whiteSpace: "pre-line"}}>
    {item.intro}
</div>;

Or you could wrap the lines with an element, such as a div or p:

return <div>
    {item.intro.split(/\n/).map(line => <div key={line}>{line}</div>)}
</div>;

Or if you want br elements between the lines, you can use fragments:

return <div>
    {item.intro.split(/\n/).map(line => <React.Fragment key={line}>{line}<br/></React.Fragment>)}
</div>;

(We can't use the shorthand <>___</> form because they don't support keys.)

But I don't like that last one as it ends with a <br/>. You can fix that, but it's more complicated:

return <div>
    {item.intro.split(/\n/).map((line, index) => index === 0 ? line : <React.Fragment key={line}>{line}<br/></React.Fragment>)}
</div>;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

How about with only css white-space:pre :


You can run the below script, Hope that will help.

const { useState , useEffect } = React;

const App = () => {

  const nstr = "Hi Vivek \nHow are you \n\nGlad to see you there";

  return (
    <div class='new-line'>
      { nstr }
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('react-root'));
.new-line {
 white-space:pre
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
2

Probably one solution if you .split() the string by \n then using .map() rendering each element from the iteration between <p> tags.

Try as the following:

return <div>
  {
     item.intro.split('\n')
               .map(e => <p>{e}</p>)
  }
</div>

You would have similar result then - this is not using JSX, just for representation:

const text = 'random\ntext\nhello';
const div = document.getElementById('text');
const result = text.split('\n').map(e => `<p>${e}</p>`);

div.innerHTML = result.join('');
<div id="text"></div>

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
0

Split the string using \n and then display them by looping the resulting array. This way the expected output will be obtained. Hope this helps

var text = "Status is unknown\nThe combination is excluded by the following restriction\nRestriction number 2. 01 Mar 12 08:03:01 0--Exclusion--OrderDeliveryTimeframe.equals(\"oneMonth\") && OrderShipping.equals(\"air\")\n\n
";
    return (
    <div>
        {text.split("\n").map((t,key) => {
            return <p key={key}>{t}</p>;
        })}
    </div>);

Nithish
  • 5,393
  • 2
  • 9
  • 24