Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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

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;
}
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>
);

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} />}
/>

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.

Simple one:

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

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

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

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>
    )
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top