Nick Moore Nick Moore - 2 months ago 47
React JSX Question

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

Answer

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