Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a multi-line text string in React

Tags:

reactjs

Suppose I have a text string that contains line-breaks, and I render it like this:

render() {     var text = "One\nTwo\nThree";     return <div>{text}</div>; } 

In HTML the line-breaks don't render as line-breaks. How should I do this in React? I don't want to convert to <br> tags and use dangerouslySetInnerHTML. Is there another way?

like image 609
Aaron Beall Avatar asked Feb 11 '16 22:02

Aaron Beall


People also ask

How do I display multiple elements in React?

In the ReactDOM. render you still can't render multiple items because react needs a root. So you can render a single component inside the ReactDOM. render and render an array of items in the internal component.

How do you wrap text in React JS?

To wrap React Native text on the screen, we can set flexWrap to 'wrap' .

Can we use multiple render in React?

Fragments in React Now you can render multiple DOM nodes. In order to do this, wrap it inside a parent div which essentially makes it a single DOM node with multiple elements inside it. Fragments in React do not deviate much from their literal meaning.


2 Answers

Make a new CSS-class

.display-linebreak {   white-space: pre-line; } 

Display your text with that CSS-class

render() {   const text = 'One \n Two \n Three';   return (       <div className="display-linebreak">          {text}       </div>   ); } 

Renders with line-breaks (Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary). Like this:

One Two Three 

You may also consider pre-wrap. More info here (CSS white-space Property).

like image 138
andersvold Avatar answered Sep 21 '22 10:09

andersvold


You could try putting divs for each line

render() {     return (<div>         <div>{"One"}</div>         <div>{"Two"}</div>         <div>{"Three"}</div>     </div>); } 

Or

render() {     var text = "One\nTwo\nThree";     return (     <div>         {text.split("\n").map((i,key) => {             return <div key={key}>{i}</div>;         })}     </div>); } 
like image 39
Sergio Flores Avatar answered Sep 18 '22 10:09

Sergio Flores