Roxy'Pro
Roxy'Pro

Reputation: 4454

Javascript string does not break in new lines

I'm trying to break string in newlines and my code looks like this:

  return (
    <>
      {`${t('UserName')}: ${Username}\n 
        ${t('FirstName')}: ${FirstName}\n
        ${t('LastName')}: ${LastName}`}
    </>
  );

When I inspect HTML it looks like it's break in new line:

enter image description here

But unfortunatelly this does not work.. in UI its displayed as :

enter image description here

Obliviously in one row..

Upvotes: 0

Views: 94

Answers (4)

Jonnel VeXuZ Dorotan
Jonnel VeXuZ Dorotan

Reputation: 468

You might want to change your React.Fragment shorthand to div? Then, add inline style:

return (
    <div style={{whiteSpace: 'pre-line'}}>
        {`${t('UserName')}: ${Username}\n 
        ${t('FirstName')}: ${FirstName}\n
        ${t('LastName')}: ${LastName}`}
    </div>
);

react-newline

Upvotes: 0

Muhammad Maaz
Muhammad Maaz

Reputation: 439

Try giving it a css property "whiteSpace: 'pre-wrap'" few days back I was facing same issue it worked for me

Upvotes: 0

95faf8e76605e973
95faf8e76605e973

Reputation: 14201

Currently, the newline characters are being treated the same as other white space because of the default white-space value which is normal

From MDN Web Docs:

white-space:normal - Sequences of white space are collapsed. Newline characters in the source are handled the same as other white space. Lines are broken as necessary to fill line boxes.

You can use white-space: pre-line if you really must do your layout with \n.

white-space:pre-line - Sequences of white space are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

document.getElementById("root").innerHTML="<div>123\n456</div>"
div {
   white-space: pre-line;
}
<div id="root"></div>

Upvotes: 0

Nikhil Singh
Nikhil Singh

Reputation: 1610

Try this

  return (
    <>
      {`${t('UserName')}: ${Username}`<br>
        `${t('FirstName')}: ${FirstName}`<br>
        `${t('LastName')}: ${LastName}`}
    </>
  );

Upvotes: 1

Related Questions