React Newline to break (nl2br)

Kevin Simper
May 29, 2015 · 1 min read

Because you know that everything in React is functions, you can't really do this

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:

{this.props.text.split(“\n”).map(function(item) {
return (
{item}
<br/>
)
})}

That is not allowed either because again React is pure functions and two functions can be next to each other.

tldr. Solution

{this.props.text.split('\n').map(function(item, key) {
return (
<span key={key}>
{item}
<br/>
</span>
)
})}

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

{this.props.text.split('\n').map((item, key) => {
return <span key={key}>{item}<br/></span>
})}

And with React Fragments

{this.props.text.split('\n').map((item, key) => {
return <Fragment key={key}>{item}<br/></Fragment>
})}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store