'How to replace /n to linebreaks in react.js?
I am trying to replace every /n
to a <br>
tag in ReactJS
. In my note.note
object there is a string with multiple /n
in it.
example note.note: test\ntest\ntest
What I have tried in ReactJS
:
{
note.note.split('\n').map(function( item, idx) {
return (
<span key={idx}>
{item}
<br/>
</span>
)
})
}
Solution 1:[1]
Your code works well:
{
note.note.split("\n").map(function(item, idx) {
return (
<span key={idx}>
{item}
<br/>
</span>
)
})
}
The OP problem was with the backend which returns \\n
and shows as \n
in the XHR preview
tab
Solution 2:[2]
An alternative to this would be to use css to display it with line breaks. This also makes it easier to copy and paste with the original line breaks as well as distinguishing between one break (\n
) and two breaks (\n\n
).
Just add the style white-space: pre-wrap;
to your element.
<div style={{whiteSpace: "pre-wrap"}}>{note.note}</div>
There are additional white-space options if that doesn't do exactly what you'd like: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
Solution 3:[3]
I just want to share this function I've been using for quite some time. It is similar to Jim Peeters' answer but no parent tags generated, just turning the \n
to <br key="<index here>" />
.
import React from 'react'
export const escapedNewLineToLineBreakTag = (string) => {
return string.split('\n').map((item, index) => {
return (index === 0) ? item : [<br key={index} />, item]
})
}
You can also convert this to a bit of a long one-liner by omitting return
and curly brackets.
export const escapedNewLineToLineBreakTag = (string) => string.split('\n').map((item, index) => (index === 0) ? item : [<br key={index} />, item])
Disclaimer: The logic behind is not from me but I can't remember where I found it. I just turned it into function form.
Solution 4:[4]
A little update for React newer versions
{
note.note
.split('\n')
.map((item, idx) => {
return (
<React.Fragment key={idx}>
{item}
<br />
</React.Fragment>
)
})
}
Solution 5:[5]
Another approach:
{
note.note.split('\n').map((item, idx) => {
return (
<span key={idx}>
{item}
<br/>
</span>
);
})
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | idmean |
Solution 2 | |
Solution 3 | jp06 |
Solution 4 | Eliecer Chicott |
Solution 5 | Jim Peeters |