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

I am trying to replace every /n to a <br> tag in ReactJS. In my note.note object there is a string with multiple /n in it.

example note.note: test\ntest\ntest

What I have tried in ReactJS:

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

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

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

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.

Read More:   TypeError: CleanwebpackPlugin is not a constructor

A little update for React newer versions

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

Another approach:

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


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts