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
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} /> ])}
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, ", ");
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