Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a comma in array.map after every element except last element in React JSX

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);
like image 578
Ajay Avatar asked Dec 19 '17 07:12

Ajay


People also ask

Can I use forEach in JSX?

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.

How do you map data from array in React JS?

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.


1 Answers

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>
like image 154
Rajesh Avatar answered Sep 18 '22 22:09

Rajesh