\n is not rendering the text in new line

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.


Solution 1:

\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.Frgament key={line}>{line}<br/></React.Fragment>)}
</div>;

...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.Frgament key={line}>{line}<br/></React.Frgament>)}
</div>;

Solution 2:

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>