Grouping React components in surrounding components

Let’s assume you have an array of data:

const content = [
    "content 1",
    "content 2",
    "content 3",
    "content 4",
    "content 5",
    "content 6",
    "content 7"
];

What you want to end up with is this:

<div class="container">
  <div class="row">
    <div class="col-md-4">content 1</div>
    <div class="col-md-4">content 2</div>
    <div class="col-md-4">content 3</div>
  </div>
  <div class="row">
    <div class="col-md-4">content 4</div>
    <div class="col-md-4">content 5</div>
    <div class="col-md-4">content 6</div>
  </div>

  <div class="row">
    <div class="col-md-4">content 7</div>
  </div>

</div>

In other words, you want to group 3 elements together by surrounding them with another element.

The solution

const App = () => {
  const content = [
    "content 1",
    "content 2",
    "content 3",
    "content 4",
    "content 5",
    "content 6",
    "content 7"
];
  const groupSize = 3;

  return (
    <div>
      {
        content.map((c) => <div className="col-md-4">{c}</div>)
          .reduce((r, element, index) => {
            // create element groups with size 3, result looks like:
            // [[elem1, elem2, elem3], [elem4, elem5, elem6], [elem7]]
            index % groupSize === 0 && r.push([]);
            r[r.length - 1].push(element);
            return r;
            }, [])
        .map((rowContent) => <div className="row">{rowContent}</div>)
      }
    </div>
  );
}

ReactDOM.render(<App />,
document.getElementById("root"))

About Author

Mathias Bothe Contact me

I am Mathias, born 38 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 14 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of bosy.com, creator of the security service platform BosyProtect© and initiator of several other software projects.