Eric Baldwin Eric Baldwin - 3 months ago 9
Javascript Question

newlines character ignored by jsx table

I am trying to create a table with a multiline string, but the string is not formatted correctly by my table. Here is the jsx:

<td>
{arr.join('\n')}
</td>


And here is the corresponding html:

<td data-reactid=".xyz">Line 1
Line 2
Line 3
Line 4</td>


But in the browser it looks like:

enter image description here

What's going on and how do I get my newlines to appear?

Answer

You've got a few options:

1) Use a block level element such as div or a p and wrap each line.

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;

        var formatted = lines.map(function(line) {
            return (<p>{line}</p>);
        });
        return (<div>{ formatted }</div>);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines }/>, 
              document.getElementById('container'));

2) Use a span with a br element:

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;

        var br = lines.map(function(line) {
            return (<span>{line}<br/></span>);
        });
        return (<div>{ br }</div>);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines } />,  
              document.getElementById('container'));

3) If you're certain there is no threat of XSS/hacks with the data, you could use dangerouslySetInnerHTML with a 'br' for each line:

var TextLines = React.createClass({      
    render: function() {
        var lines = this.props.lines;
        var content = {
            __html: lines.join('<br />')
        };     
        return (<div dangerouslySetInnerHTML={ content } />);
    }
});

var lines = ['line 1', 'line 2', 'line 3'];
React.render(<TextLines lines={ lines } />, 
             document.getElementById('container'));

The last one produces the least amount of HTML, but at a cost of potentially risky the security of the web page/user. I wouldn't use this one if the others work for you.