I\'m trying to output a list of comma separated links and this is my solution.
var Item = React.createComponent({
render: function() {
var tags = [],
Simple one:
{items.map((item, index) => (
<span key={item.id}>
{item.id}
{index < items.length - 1 && ', '}
</span>
))}
The solution without extra tags
<p className="conceps inline list">
{lesson.concepts.flatMap((concept, i) =>
[concept, <span key={i} className="separator">•</span>]
, ).slice(-1)}
</p>
generates something like
Function • Function type • Higher-order function • Partial application
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.
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} />}
/>