Grouping variable number of elements with React / JSX

时间:2015-08-14 22:43:53

标签: reactjs react-jsx

I have a situation where I have a variable number of objects in an array, and I need to create groups of three. I know that to iterate over an array I can do something like this (Fiddle - https://jsfiddle.net/o5pbttjq/):

render: function() {
    var random = Array.apply(null, Array((Math.floor(Math.random() * (15 - 1) + 1) + 1))).map(Number.prototype.valueOf,0).map(function(d,i) {return i});

    return (
        <div>
            {random.map(function(d) {
                return <p>{d}</p>
            })}
        </div>
    );
}

I can also group them like so, but it's quite ugly (Fiddle - https://jsfiddle.net/Lxqm3tzo/):

render: function() {
    var random = Array.apply(null, Array((Math.floor(Math.random() * (15 - 1) + 1) + 1))).map(Number.prototype.valueOf,0).map(function(d,i) {return i});

    var content = "<div>";

    random.forEach(function(d, i) {
        if (i % 3 === 0 && i !== 0) {
          content += "</div><div>"
        }
        content += "<p>" + d + "</p>"
    })
    content += "</div>"
    return (
        <div dangerouslySetInnerHTML={{__html: content}}></div>
    );
}

How can I create groups of a variable number of objects with JSX?

0 个答案:

没有答案