Because you know that everything in React is functions, you can’t really do this
1 | this.state.text.replace(/(?:\r\n|\r|\n)/g, '<br />') |
Since that would return a string with DOM nodes inside, that is not allowed either, because has to be only a string.
You then can try do something like this:
1 | {this.props.text.split(“\n”).map(function(item) {<br> return (<br> {item}<br> <br/><br> )<br>})} |
That is not allowed either because again React is pure functions and two functions can be next to each other.
tldr. Solution
1 | {this.props.text.split('\n').map(function(item, key) {<br> return (<br> <span key={key}><br> {item}<br> <br/><br> </span><br> )<br>})} |
Now we’re wrapping each line-break in a span, and that works fine because span’s has display inline. Now we got a working nl2br line-break solution.
And ES6 version
1 | {this.props.text.split('\n').map((item, key) => {<br> return <span key={key}>{item}<br/></span><br>})} |
And with React Fragments
1 | {this.props.text.split('\n').map((item, key) => {<br> return <code><Fragment key={key}></code>{item}<br/></Fragment><br>})} |
From: https://medium.com/@kevinsimper/react-newline-to-break-nl2br-a1c240ba746