Skip to content
Advertisement

Replace ‘n’ in String variable to so that it shows line break when displayed in

I have a textarea in React that also accepts newLine characters. It is correctly stored in mongoDB with the newLine characters. When I retrieve it back to React and try to display it in table <td>, it shows with spaces. But if I put it on console, it is correctly shown. I guess that is because in HTML newline character is <br >. How can I do this?

I tried replacing ‘n’ with <br> using replace(), but then <br> gets concatenated as a string literal.

“items” shown in mongoDB

items shown in mongoDB


How its displayed in table

How its displayed in table




Correctly shown in console

Correctly shown in console


Code

Code

Advertisement

Answer

As MrBens suggested, the simplest solution is to use the pre (preformatted text) tag. For example:

 <td><pre>This is
 two lines</pre></td>

Would result in:

This is

two lines

There’s also a similar CSS style, whitespace: pre or whitespace: pre-wrap. The MDN has details about that also.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement