Is there a way to have line breaks in text without using dangerouslySetInnerHTML?

11.5k views Asked by At

I need to replace \n to <br>. But it is taking this as in text.

How can I do that without using dangerouslySetInnerHTML?

4

There are 4 answers

4
Chris Hawkes On BEST ANSWER
var yourNewValueWithBr = yourOldValue.replace(/\n/g,"<br />");

After replacing this text, you will need to use dangerouslySetInnerHTML to render it as HTML.

0
Victor On

This solution replaces \n to <br> and works without dangerouslySetInnerHTML:

render: function() {
  var lines = this.props.text.split("\\n").map(function(line, n){
      return (n == 0) ? [line] : [<br />, line];
  });
  return <div>{lines}</div>;
}

But if you need HTML formatting, and you're sure that your text is safe from XSS, I would recommend to stick with dangerouslySetInnerHTML and a regex replace like Chris Hawkes said.

1
mik01aj On

Insert the text as you normally would, and fix the line breaks with CSS:

white-space: pre-wrap;

Don't use dangerouslySetInnerHTML unless you really have to.

0
Prajesh Mishrikotkar On

You could use style={{whiteSpace: 'pre-wrap'}} for the wrapping div.

Now you will break line without dangerouslySetInnerHTML and <BR>

You can check browser compatibility over here: CSS SPEC