Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering comma separated list of links

I'm trying to output a list of comma separated links and this is my solution.

var Item = React.createComponent({   render: function() {      var tags = [],         tag;      for (var i = 0, l = item.tags.length; i < l; i++) {       if (i === item.tags.length - 1) {         tag = <span><Tag key={i} tag={item.tags[i]} /></span>;       } else {         tag = <span><Tag key={i} tag={item.tags[i]} /><span>, </span></span>;       }       tags.push(tag);     }      return (       <tr>         <td>           {item.name}         </td>         <td>           {tags}         </td>       </tr>     );    } }); 

I was just wondering if there was a better, more clean way to accomplish this?

Thanks

like image 565
Nick Avatar asked May 12 '14 20:05

Nick


2 Answers

Simply

{tags.map((tag, i) => <span key={i}>     {i > 0 && ", "}     <Tag tag={tag} /> </span>)} 


In React 16 it can be done even more simpler:

{tags.map((tag, i) => [     i > 0 && ", ",     <Tag key={i} tag={tag} /> ])} 
like image 94
imos Avatar answered Sep 21 '22 23:09

imos


At Khan Academy we use a helper called intersperse for this:

/* intersperse: Return an array with the separator interspersed between  * each element of the input array.  *  * > _([1,2,3]).intersperse(0)  * [1,0,2,0,3]  */ function intersperse(arr, sep) {     if (arr.length === 0) {         return [];     }      return arr.slice(1).reduce(function(xs, x, i) {         return xs.concat([sep, x]);     }, [arr[0]]); } 

which allows you to write code like:

var tags = item.tags.map(function(tag, i) {     return <Tag key={i} tag={item.tags[i]} />; }; tags = intersperse(tags, ", "); 
like image 33
Sophie Alpert Avatar answered Sep 21 '22 23:09

Sophie Alpert