TransWikia.com

Javascript string does not break in new lines

Stack Overflow Asked by Roxy'Pro on November 4, 2021

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

4 Answers

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

Answered by Jonnel VeXuZ Dorotan on November 4, 2021

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

Answered by Muhammad Maaz on November 4, 2021

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>123n456</div>"
div {
   white-space: pre-line;
}
<div id="root"></div>

Answered by 95faf8e76605e973 on November 4, 2021

Try this

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

Answered by Nikhil Singh on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP