0

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?

1 Answer 1

1

The following will work without having to set the innerHTML. See the fiddle here: https://jsfiddle.net/kuvvd513/8/

var Hello = React.createClass({
    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 allGroups = [];
        var group = [];
        random.forEach(function(d, i) {    
            if (i % 3 === 0 && i !== 0) {
                 allGroups.push(<div> {group} </div>);        
                 group = [];
            }
            group.push(<p> {d} </p>);
        }.bind(this));
        allGroups.push(<div> {group} </div>);

        return (
            <div>
                {allGroups}
            </div>
        );
    }
});

React.render(<Hello name="World" />, document.getElementById('container'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.