React - adition of more objects into one

Hello, I define JSX object and then I want to add them up. Using for cycle. I am bad at explaining since I don’t know terminology that well, but have a look at the example. I need the number of those buttonlines to vary, so I need to make it into a function. Any advice? Simply adding them together by + doesnt work.


If I understand what you want …

There are different ways to do it, and easier ways to do it than this, but this is clear and easy to read:

class Main extends React.Component {
  makeSpan(a, b) {
    return <h5>{a}, {b}</h5>
  makeSpans(a) {
    const arr = [];
    for (let i=0; i<=14; i++) {
      arr.push(this.makeSpan(a, i))
    return arr;
  render() {
    return (

There is a pen here.

1 Like

Thank you very much. That’s exactly what I was looking for!
Why does it works as an array, and not as a sum of elements? Because every object is part of array, not a string?

Because {this.makeSpans(127)} returns an array of elements and React knows how to handle an array of elements. This is a very common pattern in React. Very often you will also map over an existing array to return an array of elements in much the same way.

1 Like