React.js every nth element adds an opening tag or a closing tag

I am having problems with this logic, since response / jsx does not allow adding non-blocking tags to the array / child component. For example, using bootstrap css, I want to add a row for each 4 columns.

So the logic is this:

Add the starting line ex:, <div className="row">then loop inside that line, and each loop adds an ex: column <div className="column>{this.data}</div>when the loop reaches 4 with if(i % 4 == 0)and adds a closing tag </div>when adding a new line tag <div className="row">;

The code below will work in another language, but in response this is not feasible, because we click on the closing tag and the opening tag (which is not valid jsx):

generateColumns(columns) {
 let newColumns = [];

 columns.forEach(function(column, idx) {
  newColumns.push( <div className="column"> some data </div> );

  if (idx % 4 == 0) {
   // Here we end the row and start a new row, works in any other language.
   newColumns.push( </div> <div className="row"> );
  }
 });

 // This array now has the proper tags for opening a row every 4th item and closing it.
 return newColumns;
},
render() {
   return (
     <div className="row">
       {this.generateColumns(this.props.columns)}
     </div>
   )
}

Expected Result:

<div class="row">
  <div class="column">
   Some data
  </div>
  <div class="column">
   Some more data
  </div>
  <div class="column">
   Other data
  </div>
  <div class="column">
   Something else
  </div>
</div>
<div class="row">
  <div class="column">
   Some data
  </div>
  <div class="column">
   Some more data
  </div>
  <div class="column">
   Other data
  </div>
  <div class="column">
   Something else
  </div>
</div>

//the above would be repeated and new rows would appear every 4 columns.

+4
2
render() {
   const rows = array_chunk(this.props.columns, 4)
   return (
     {
       rows.map((row) => (
         <div className="row">
         {
           row.map((col) => (
             <div className="col">{ col }</div>
           ))
         }
         </div>
       ))
     }
   )
}

array_chunk ( lodash)

module.exports = function chunks(arr, size) {
  if (!Array.isArray(arr)) {
    throw new TypeError('Input should be Array');
  }

  if (typeof size !== 'number') {
    throw new TypeError('Size should be a Number');
  }

  var result = [];
  for (var i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, size + i));
  }

  return result;
};
+17

.

render() {
    let rows = [],
        cols = []
    let index = 0
    const totalCols = 20;

    for (index; index < totalCols; index++) {
        cols.push(<div class="col" key={index}/>)
        if ((index + 1) % 4 == 0) {
            rows.push(
                <div class="row" key={index}>
                    {cols}
                </div>
            )
            cols = []
        }
    }
    return (
        <div class="container">
            {rows}
        </div>
    )
}
0

All Articles