Newline in react string [Solved]

Newline in react string [Solved]
0

#1

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…


#2

To use <br> you have to use dangerouslySetInnerHTML


#3

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


#4

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


#5

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


#6

Well I fixed this with:

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

#7

Sorry, I don’t understand what you mean.


#8

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.


#9

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:


#10

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:


#11

Yeah, good piece of advice! :slight_smile:


#12

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


#13

Thank you, very interesting!


#14

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


#15

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