Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
    )
  })
}
like image 661
Jim Peeters Avatar asked Nov 04 '16 08:11

Jim Peeters


4 Answers

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

like image 53
Tom Prats Avatar answered Nov 08 '22 11:11

Tom Prats


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

like image 31
tomloprod Avatar answered Nov 08 '22 10:11

tomloprod


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.

like image 4
jp06 Avatar answered Nov 08 '22 10:11

jp06


A little update for React newer versions

{
  note.note
    .split('\n')
    .map((item, idx) => {
      return (
        <React.Fragment key={idx}>
          {item}
          <br />
        </React.Fragment>
      )
    })
}
like image 2
Eliecer Chicott Avatar answered Nov 08 '22 11:11

Eliecer Chicott