1

very simple question, when I loop through array when rendering react compnent with .map function, say:

render() {
        let board = this.props.board;

        return (
            <div>
                 {
                   board.map((piece,index) => {
                       return (
                           <Piece data={piece}/>
                       );
                   })
                 }
            </div>
        );
    }

I'm trying to add a break line every 5 pieces so (index % 5 == 0) add <br /> before the <Piece />
when I try to concatinate with + or to do something like this:

board.map((piece,index) => {
      return (
                (index % 5 == 0) ? <br /> : ''
                <Piece data={piece}/>
             );
})

I'm getting an output of matrix of [Object object]'s

1 Answer 1

9

Return an array of [ <br />, <Piece> ] if the condition holds and return just the Piece component otherwise. See the fiddle.

The relevant piece of code is this:

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

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

Also, put key on the components you return from map or other ways that return array-like instances. This way, React doesn't need to take out all the generated components and replace them on each render, but can just find them under the key and update their attributes. Check out Reconciliation in React docs to learn more.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much! That makes sense. A question I have in my head now, if I want to wrap every 5 items with a div, how do I do that?
Please post a new question on Stack Overflow and link to it in a comment, I'll be happy to answer it.
First of all here's a jsfiddle with a little fix so it work for objects and not only for array of numbers (just added the index to the map loop) jsfiddle.net/s048wnoc. and here is a link to my second question, stackoverflow.com/questions/33856949/… , thank you very much, appriciate it.

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.