I have a string (an address) containing commas that I wish to delimit to line-breaks inside some JSX. Doing the following merely outputs the <br />
as a string:
{address.split(',').join('<br />')}
How can I do what I need to do, preferably retaining the commas?
Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.
To convert comma separated text into separate lines, you need to use trim() along with split() on the basis of comma(,).
Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.
You can try wrap each address in p
tag and don't use <br />
,
var Component = React.createClass({
render: function() {
var addresses = this.props.addresses.split(',').map(function (address, index) {
return <p key={index}>{ address }</p>;
});
return <div className="addresses">{addresses}</div>;
}
});
Example
To delimit based on commas, turning commas into line-breaks, while "preferably retaining the commas" (not sure you meant you want to retain them in the output, but interpreting that as such) you can try the following (works for me):
let newAddress = address.split(',').map(line => <span>{line},<br/></span>);
// span tag here only in order for JSX to accept br tag
You can simply insert <br/>
between the lines via reduce
:
{address.split(',').reduce((all, cur) => [
...all,
<br/>,
cur
])}
Sometimes you want to use line breaks and not paragraphs. In that case, you can do:
function convertNewLines(_text) {
let lines = _text.split('\n');
let elements = [];
for (let i=0; i<lines.length; i++) {
elements.push(lines[i]);
if (i < lines.length-1) {
elements.push(<br key={i}/>);
}
}
return elements;
}
This avoids the use of dangerously setting inner HTML.
(FWIW I figured this out by using the Babel REPL.)
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