How to replace /n to linebreaks in react.js?

An alternative to this would be to use css to display it with line breaks. This also makes it easier to copy and paste with the original line breaks as well as distinguishing between one break (\n) and two breaks (\n\n).

Just add the style white-space: pre-wrap; to your element.

<div style={{whiteSpace: "pre-wrap"}}>{note.note}</div>

There are additional white-space options if that doesn't do exactly what you'd like: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space


I just want to share this function I've been using for quite some time. It is similar to Jim Peeters' answer but no parent tags generated, just turning the \n to <br key="<index here>" />.

import React from 'react'

export const escapedNewLineToLineBreakTag = (string) => {
  return string.split('\n').map((item, index) => {
    return (index === 0) ? item : [<br key={index} />, item]
  })
}

You can also convert this to a bit of a long one-liner by omitting return and curly brackets.

export const escapedNewLineToLineBreakTag = (string) => string.split('\n').map((item, index) => (index === 0) ? item : [<br key={index} />, item])

Disclaimer: The logic behind is not from me but I can't remember where I found it. I just turned it into function form.


Your code works well:

{
    note.note.split("\n").map(function(item, idx) {
        return (
            <span key={idx}>
                {item}
                <br/>
            </span>
         )
    })
}

The OP problem was with the backend which returns \\n and shows as \n in the XHR preview tab


A little update for React newer versions

{
  note.note
    .split('\n')
    .map((item, idx) => {
      return (
        <React.Fragment key={idx}>
          {item}
          <br />
        </React.Fragment>
      )
    })
}