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!" />
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With