How to render a multi-line text string in React

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?


Solution 1:

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).

Solution 2:

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>);
}

Solution 3:

You could use CSS property "white-space: pre". I think this is the easiest way to handle this.