简体   繁体   中英

map function loop when rendering with ReactJS and concat JSX syntax

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM