How can I add a trailing comma after every element of an array for making a list like:
INV, INV, INV, INV
Note that the last element doesn't have a trailing comma
Currently iterating the list with array.map
:
var List = React.createClass({
render: function() {
return (
<div>
{this.props.data.map(function(item) {
return <div>{item}</div>;
})}
</div>
);
}
});
var data = ["red", "green", "blue"];
React.render(<List data={data} />, document.body);
forEach method can be used when you need to call a function for every element in an array. However, forEach() can't be used to iterate over an array directly in your JSX code.
Given the code below, we use the map() function to take an array of numbers and double their values. We assign the new array returned by map() to the variable doubled and log it: const numbers = [1, 2, 3, 4, 5]; const doubled = numbers. map((number) => number * 2);console.
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>
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