3

I have my code as below. template literals not creating multiline string in span tag, where as it is creating multiline in console.

import React, {Component} from 'react';

import ReactDOM from 'react-dom';


class MyApp extends Component {

    render() {

        console.log(`string text line 1
        string text line 2`);

        let test = `dfas dss
        sdassas`;

        return (
            <span>{test}</span>
        )
    }
}

ReactDOM.render(
    <MyApp />,
    document.getElementById('app')
  );
  • For HTML that is one space only. Your output is HTML – marciojc Nov 13 '17 at 19:54
  • 1
    The string is multiline, you can see it if you use a `
    ` or `white-space: pre;` HTML collapses all whitespace into a single space for display purposes, unless instructed otherwise
    – Ruan Mendes Nov 13 '17 at 19:56

2 Answers2

5

HTML collapses whitespace into a single space. See Why does HTML require that multiple spaces show up as a single space in the browser?

The easiest solution would be to tell that span that it should not collapse whitespace.

The following snippet shows you that this is not related to React, and how to display newlines in HTML

<h2>Using white-space: pre</h2>
<span style="white-space: pre">       
    
    Hello this
    
    has new lines
</span>
    
<h2>Collapsing white space</h2>
<span>
    
    Hello this
    
    has new lines
    
</span>
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
4

When using JSX this is what solved it for me:

  <span style={{ whiteSpace: 'pre' }}>
      {`
          Some
          multiline
          text
      `}
  </span>
Bjørnar Hvidsten
  • 859
  • 12
  • 15