Aaron Aaron - 3 months ago 52
React JSX Question

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?

Answer

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 => {
            return <div>{i}</div>;
        })}
    </div>);
}