Rendering comma separated list of links

后端 未结 10 1575
再見小時候
再見小時候 2020-12-24 00:58

I\'m trying to output a list of comma separated links and this is my solution.

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

    var tags = [],
         


        
相关标签:
10条回答
  • 2020-12-24 01:33

    Simple one:

    {items.map((item, index) => (
        <span key={item.id}>
          {item.id}
          {index < items.length - 1 && ', '}
        </span>
     ))}
    
    0 讨论(0)
  • 2020-12-24 01:36

    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 讨论(0)
  • 2020-12-24 01:39

    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.

    0 讨论(0)
  • 2020-12-24 01:39

    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} />}
    />
    
    0 讨论(0)
提交回复
热议问题