5

Here are some ajax calls returns <br /> in their data, while I found it was hard to handle.

Here is what I got for now, but not working at all. The string was split correctly, while react gave me several <span></span> tags without proper <br /> line breaks.

const breakLine = text => {
    const regex = /<br\s*[\/]?>/gi

    return text.split(regex).map(
        line => line.match(regex) ? React.createElement('br') : line
    )
}

const Text = ({ content }) => <p>
    { breakLine(content) }
<p>

// Usage
<Text content="Here are some <br /> Lines <br> to break!" />
namelos
  • 133
  • 1
  • 1
  • 6
  • There is now a far better way to do this in modern versions of React. See https://stackoverflow.com/a/36377593/2237142 – firetiger77 Oct 30 '19 at 23:15

2 Answers2

3

When you split using the regex your array will not contain the <br /> tags as split removes the delimiter.

let splitText = text.split(regext);
// ["Here are some ", " Lines ", " to break!"]

Which makes your ternary always hit the false clause and only return the actual line.

One way of doing it can be found in this answer

Working example regex courtesy of @JonMayer

function breakLine(text) {
    var br = React.createElement('br');
    var regex = /(<br \/>)/g;
    return text.split(regex).map(function(line, index) {
        return line.match(regex) ? <br key={"key_" + index} /> : line;
    });
}

var Text = React.createClass({
    render: function() {
        return <div>{ breakLine(this.props.content) }</div>;
    }
});

React.render(<Text content="Here are some <br /> Lines <br /> to break!" />, document.body);
Community
  • 1
  • 1
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • 2
    Oh, my... I was testing with `\n`, find it works so I didn't aware of the strange regex behaviour. You are awesome dude! – namelos Nov 07 '15 at 09:26
1

You're most likely looking for dangerouslySetInnerHTML. The following code will work without needing the breakLine function.

const Text =  ({content}) => {
    return (
       <p dangerouslySetInnerHTML={{__html: content}}></p>
    );
};
joemaddalone
  • 146
  • 2