How to add a comma in array.map after every element except last element in React JSX
As commented you can use:
array.map((item, index) => ({ (index ? ', ': '') + item }))
Also, since you want to display text inline, using a div is not appropriate. Instead you can/should use an inline element like span
var List = React.createClass({
render: function() {
return (
<div>
{
this.props.data.map(function(item, index) {
return <span key={`demo_snap_${index}`}>{ (index ? ', ' : '') + item }</span>;
})
}
</div>
);
}
});
var data = ["red", "green", "blue"];
ReactDOM.render(<List data={data} />, demo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="demo"></div>
Use the CSS adjacent sibling combinator (+
) to add pseudo element (::before
) with a comma to all sibling items, but the 1st:
var List = React.createClass({
render: function() {
return (
<div>
{this.props.data.map(function(item) {
return <div className="item">{item}</div>;
})}
</div>
);
}
});
var data = ["red", "green", "blue"];
ReactDOM.render(<List data={data} />, demo);
.item {
display: inline-block;
}
.item + .item::before {
display: inline-block;
white-space: pre;
content: ", ";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="demo"></div>
What you can do is, check the index of item, if index is not equals to the last item render the ,
otherwise nothing.
Write it like this:
{
this.props.data.map((item, i, arr) => <span>{item} {i != (arr.length-1) ? ',' : ''}</span>)
}
You can also store the total data length in a separate variable and instead of checking the arr.length
in each iteration check with that variable.
Working example:
var List = React.createClass({
render: function() {
return (
<div>
{
this.props.data.map((item, i, arr) => <span>{item} {i != (arr.length-1) ? ', ' : ''}</span>)
}
</div>
);
}
});
var data = ["red", "green", "blue"];
ReactDOM.render(<List data={data} />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>