61

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

10 Answers 10

124

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} />
])}
13
  • 1
    Sweet and Simple!
    – Mrchief
    Commented Feb 17, 2017 at 19:54
  • @imos Would you mind explaining this a bit? {!!i && ", "}
    – Macxim
    Commented Jul 29, 2017 at 16:59
  • 2
    @Macxim This line prints comma before each tag except first. Expression !!i just converts i to boolean. Also !!i can be replaced by i > 0.
    – iimos
    Commented Jul 31, 2017 at 6:51
  • @imos Thank you very much.
    – Macxim
    Commented Jul 31, 2017 at 13:33
  • 3
    One of the best value-per-character answers, I've ever seen. Should I propose migrating this to Code Golf? =) Commented Dec 6, 2017 at 3:10
77

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, ", ");
3
  • 1
    Any idea how you could pass an element (like a <span/>) as the second parameter? It does work, but I get a warning about not specifying a key... I tried by wrapping the <span> in a function (and generate a random key) but that doesn't seem very correct or to work. Commented Sep 15, 2016 at 21:13
  • 1
    I just realised this is the way I could do it; pass a function as the separator that accepts and idx and then use the index of the array reducer as a key. Commented Sep 15, 2016 at 21:20
  • 1
    Something like in this gist Commented Sep 15, 2016 at 21:26
9

Or simply write the list items to an unordered list and use CSS.

var Item = React.createComponent({
  render: function() {

    var tags = this.props.item.tags.map(function(i, item) {
      return <li><Tag key={i} tag={item} /></li>
    });

    return (
      <tr>
        <td>
          {this.props.item.name}
        </td>
        <td>
          <ul className="list--tags">
            {tags}
          </ul>
        </td>
      </tr>
    );

  }
});

And the CSS:

.list--tags {
    padding-left: 0;
    text-transform: capitalize;
}

.list--tags > li {
    display: inline;
}

.list--tags > li:before {
    content:',\0000a0'; /* Non-breaking space */
}
.list--tags > li:first-child:before {
    content: normal;
}
3
  • 1
    It's really not explicit this way
    – S.C.
    Commented Jul 8, 2015 at 10:57
  • I like this approach. I just used .csv class and make it work with any element: .csv>*, not just ui>li and it's perfectly understandable
    – Liero
    Commented May 9, 2016 at 12:23
  • I like this approach because it's semantic, and as far as I can tell works better for accessibility.
    – tenor528
    Commented May 12, 2017 at 21:37
3
import React from 'react';
import { compact } from 'lodash';

// Whatever you want to separate your items with commas, space, border...
const Separator = () =>  { ... }; 

// Helpful component to wrap items that should be separated
const WithSeparators = ({ children, ...props }) => {

  // _.compact will remove falsey values: useful when doing conditional rendering
  const array = compact(React.Children.toArray(children));

  return array.map((childrenItem, i) => (
    <React.Fragment key={`${i}`}>
      {i > 0 && <Separator {...props} />}
      {childrenItem}
    </React.Fragment>
  ));
};

const MyPage = () => (
  <WithSeparators/>
    <div>First</div>
    {second && (<div>Maybe second</div>)}
    {third && (<div>Maybe third</div>)}
    <div>Fourth</div>
  </WithSeparators>
);
2

A function component that does the trick. Inspired by @imos's response. Works for React 16.

const Separate = ({ items, render, separator = ', ' }) =>
  items.map((item, index) =>
    [index > 0 && separator, render(item)]
  )

<Separate
  items={['Foo', 'Bar']}
  render={item => <Tag tag={item} />}
/>
1

Here's a solution that allows <span>s and <br>s and junk as the separator:

const createFragment = require('react-addons-create-fragment');

function joinElements(arr,sep=<br/>) {
    let frag = {};
    for(let i=0,add=false;;++i) {
        if(add) {
            frag[`sep-${i}`] = sep;
        }
        if(i >= arr.length) {
            break;
        }
        if(add = !!arr[i]) {
            frag[`el-${i}`] = arr[i];
        }
    }
    return createFragment(frag);
}

It filters out falsey array elements too. I used this for formatting addresses, where some address fields are not filled out.

It uses fragments to avoid the warnings about missing keys.

1

To add to the great answers above Ramda has intersperse.

To comma separate a bunch of items you could do:

const makeLinks = (x: Result[]) =>
  intersperse(<>,</>, map(makeLink, x))

Pretty succinct

0

Simple one:

{items.map((item, index) => (
    <span key={item.id}>
      {item.id}
      {index < items.length - 1 && ', '}
    </span>
 ))}
0

The solution without extra tags

<p className="conceps inline list">
  {lesson.concepts.flatMap((concept, i) =>
    [concept, <span key={i} className="separator">&#8226;</span>]
  , ).slice(-1)}
</p>

generates something like

Function • Function type • Higher-order function • Partial application

0

The easiest way to do

const elementsArr = ["a", "b", "c"];
let elementsToRender = [] ;
elementsArr.forEach((element, index) => {
    let elementComponent = <TAG className="abc" key={element.id}>{element}</TAG>
    elementsToRender.push(elementComponent);
    if(index !== (elementsArr.length - 1)){
        elementsToRender.push(", ");
    }
});

render(){
    return (
        <div>{elementsToRender}</div>
    )
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.