Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React display line breaks from saved textarea

Using Facebook React. In a settings page, I have a multiline textarea where a user can enter multiline text (in my case, an address).

<textarea value={address} /> 

When I try to display the address, so something like {address}, it doesn't show the line breaks and is all on one line.

<p>{address}</p> 

Any ideas how to solve this?

like image 717
denislexic Avatar asked Mar 28 '16 10:03

denislexic


People also ask

How do I preserve line breaks in textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' .

How do you show line breaks in React?

To display line breaks from saved text area in a React component, we can set the white-space CSS property to pre-line . We have the p-wrap class that has the white-space CSS property set to pre-line . Then we apply that class to the p element.

How do you store line breaks in database?

Just put the output text between <pre></pre> tags, that will preserve the line breaks.

How do you use BR in React JS?

Using <br> Tag in React We use the <br> tag in HTML to break the string in between or break the section; hence, if you want to break the string, the <br> tag will be placed, and the followed content will move to the next line. For example, there is one string, and you can use the <br> , as given below.


1 Answers

There's no reason to use JS. You can easily tell the browser how to handle newline using the white-space CSS property:

white-space: pre-line; 

pre-line

Sequences of whitespace are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

Check out this demo:

<style>    #p_wrap {      white-space: pre-line;    }  </style>    <textarea id="textarea"></textarea>  <p id="p_standard"></p>  <hr>  <p id="p_wrap"></p>  <script>    textarea.addEventListener('keypress', function(e) {      p_standard.textContent = e.target.value      p_wrap.textContent = e.target.value    })  </script>

browser support for pre-line

like image 150
enapupe Avatar answered Oct 08 '22 13:10

enapupe