Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make <br /> from string works in react

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!" />
like image 476
namelos Avatar asked Sep 26 '22 06:09

namelos


1 Answers

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);
like image 120
Henrik Andersson Avatar answered Sep 30 '22 08:09

Henrik Andersson