2

In a react application I am working on there is a condition that:

when a string has a new line character the

<p>{string}</p> tag in which string is to be displayed should be replaced with HTML new line character.

But of course this does not work.

Things I have already tried but did not work for me:

const string = Hello\nHii

  1. <p>{string.replace('\n', <br />)}</p>

output:

Hello<br />Hii

  1. <p>{string.replace('\n', &amp;)}</p>

output:

Hello Hii

I found the above suggestions in the following answers:

the val of a textarea doesnt take new lines into account

HVenom
  • 712
  • 1
  • 10
  • 25
  • Possible duplicate of [Render HTML string as real HTML in a React component](https://stackoverflow.com/questions/39758136/render-html-string-as-real-html-in-a-react-component) – matiit Oct 31 '18 at 09:10
  • 1
    Not sure if this is helpful, but have you tried splitting the string around `\n`, and then generating a new `

    {string}

    ` for each element of the resulting split?
    – Daniel Arthur Oct 31 '18 at 09:12

1 Answers1

5

There are two options.

  1. Using pre tag or css property white-space: pre:

    <p><pre>{string}</pre></p>

  2. Using dangerouslySetInnerHTML:

    <p dangerouslySetInnerHTML={{__html: string.replace('\n', '<br />')}}></p>

UjinT34
  • 4,784
  • 1
  • 12
  • 26