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?
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' .
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.
Just put the output text between <pre></pre> tags, that will preserve the line breaks.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With