Skip to content
Advertisement

n is not rendering the text in new line

I am having some dynamic JSON strings like below:

Status is unknownnThe combination is excluded by the following restrictionnRestriction number 2. 01 Mar 12 08:03:01 0--Exclusion--OrderDeliveryTimeframe.equals("oneMonth") && OrderShipping.equals("air")nn

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 nn]/g, "n")}
     <br/>

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

Advertisement

Answer

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>;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement