Ad

Reactjs Have
Wrapper The Elements On Every 4th Elements

- 1 answer

React group 4 items in a div with class row. At the moment you can see below I have a <div> group around the articles.

// articles is array of article object
<div className="row">
    <section className="section--6-or-4-items section-featured campaign-teasers">
        {articles.map(item => <Teaser {...item} key={item.id} />)}
    </section>
</div>

Should I create a new component which have <div> wrapper around and only accept 4 arrays at a time to render out the articles.

Ad

Answer

Your best bet here is to build your array of articles into an array of 4-length arrays. You can do this using lodash's handy chunk method.

Once you've chunked your articles, you can iterate over them in your JSX, something like this:

const sections = chunk(articles, 4);

return (
  <div className="row">
    {sections.map((articles, i) => (
      <section className="..." key={i}>
        {articles.map(item => <Teaser {...item} key={item.id} />)}
      </section>
    )}
  </div>
);

Edit: If you don't want to use lodash, you can use reduce to great effect:

function chunk(array, size) {
  return array.reduce((chunks, item, i) => {
    if (i % size === 0) {
      chunks.push([item]);
    } else {  
      chunks[chunks.length - 1].push(item);
    }
    return chunks;
  }, []);
}
Ad
source: stackoverflow.com
Ad