Newline in react string [Solved]

Newline in react string [Solved]

How can you add a new line in a react string?
I have the following prop:

text: 'Line one... \n Line two'

and I would like the output to be:

Line one
Line two

I tried with \n even with <br /> but nothing works.
I even tried with

let newText = text.split('\n').map(i => {
    return <p>{i}</p>

But nothing shows up in the web page… I might do something wrong then…

1 Like

To use <br> you have to use dangerouslySetInnerHTML

1 Like

Heard that it is ‘dangerous’ to use it! :smiley:


Yeah :smiley: if your string can have html tag you should “validate” it


Also, you tried setting the tag in your stylesheet to display:block? Or using flex box to create a column?


Well I fixed this with:

let newText = text.split('\n').map((item, i) => {
    return <p key={i}>{item}</p>;
1 Like

Sorry, I don’t understand what you mean.


Why try creating a new line in JavaScript when you’re essentially storing an array of <p> tags? It would make more sense to me to change the way the elements are positioned on the page.


Because I have a text which changes when the state changes. That means that I have different lines depending on the state.
I am using <p> tags, to make that line break.

Hope it makes sense. :stuck_out_tongue:


Only a little advice with ES6, if you have to return a function ( <tag></tag> babel transform it in a single function ) you can write in this way:

let newText = text.split ('\n').map ((item, i) => <p key={i}>{item}</p>);

Maybe you already know it, but for future generations could be useful :grin:

1 Like

Yeah, good piece of advice! :slight_smile:


I see you marked this solved, but in case someone visits this later:

If you are adding multiple lines of text with \n to a div, add the following to the css for the div in question:

div {
  white-space: pre-wrap;

Simple example


Thank you, very interesting!


Thanks! I spant few hours before to find this solution and it’s perfectly work for me!


Thanks a lot! this is the neatest solution i found around web :slight_smile:


“pre-wrap” non-support ie and edge.


another little advice, react automatically uses the index as a key if no other key is provided so key={i} is redundant :slight_smile: