Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  100] [ 5]  / answers: 1 / hits: 12013  / 4 Years ago, wed, may 13, 2020, 12:00:00

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.


More From » reactjs

 Answers
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.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>;

[#3831] Sunday, May 10, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;