How to render a multi-line text string in React

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

Here the cleanest solution (afaik):

   render(){
      return <pre>
             Line 1{"\n"}
             Line 2{"\n"}
             Line 3{"\n"}
      </pre>
   }

Instead of you can also use <div style={{whiteSpace:"pre"}}>, or any other html block element (like span or p with this style attribute)


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


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

Tags:

Reactjs