0

I want to wrap a ReactJS component with div, but I want to wrap the elemnt every 5 items only. I've managed (with little help) to add line break every 5 items.

here's the code:

var Item = React.createClass({
    render: function() {
        return <span> {this.props.num}</span>;
    }
});

var Hello = React.createClass({
    render: function() {
        var items = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ];

        return <div>{items.map(function (i,index) {
            if (index % 5 === 0) {
                return [ <br />, <Item key={i} num={i} /> ];
            }

            return <Item key={i} num={i} />;
        })}</div>;
    }
});

ReactDOM.render(
    <Hello name="World" />,
    document.getElementById('container')
);

here's a JSFIDDLE

i still want to use the .map function to loop through the array, it is more convenient and intuitive.

the question is how do I wrap it with a <div> and not <br> every 5 lines?

sorry for the confusion here is an explanation: wanted:

<div>0 1 2 3 4</div>
<div>5 6 7 8 9</div>

what I have:

0 1 2 3 4 <br />
5 6 7 8 9 <br />
5
  • What's the question? Commented Nov 22, 2015 at 16:10
  • I want to wrap a ReactJS component with div, but I want to wrap the elemnt every 5 items only. how do I do it right? Commented Nov 22, 2015 at 16:12
  • I still don't get it. Maybe desired vs. actual output structure would help. Commented Nov 22, 2015 at 16:13
  • that fiddle seems to be working Commented Nov 22, 2015 at 16:13
  • sorry for confusion, I added example Commented Nov 22, 2015 at 16:16

1 Answer 1

5

Check out this JSFiddle. It breaks the input array into batches of five and wraps each of these batches in a div. These divs--each having five Item components as children--are all wrapped in another div, which is returned.

Here's the render function:

render: function() {
    var items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ];
    var fives = [];
    while(items.length) {
        fives.push(items.splice(0, 5));
    }
    return (
        <div>
            {fives.map(function (five, index) {
                return (
                    <div key={index}>
                        {five.map(function (item, index) {
                            return (<Item key={index} num={item} />);
                        })}
                    </div>
                );
            })}
        </div>
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

clever solution!

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.