react loop code example

Example 1: react for loop in render

render: function() {
  const elements = ['one', 'two', 'three'];
  return (
    <ul>
      {elements.map((value, index) => {
        return <li key={index}>{value}</li>
      })}
    </ul>
  )
}

Example 2: react for loop

<tbody>
  {[...Array(10)].map((x, i) =>
    <ObjectRow key={i} />
  )}
</tbody>

Example 3: react create pillbox for each chunk of array

const brandGroups = brandNames.map((e, i) => {
      return i % chunkSize === 0 ? brandNames.slice(i, i + chunkSize) : null;
    }).filter(e => { return e; });

    const renderBrandsItems = () => {
      const ThreePlusBrands = `${brandNames.slice(0, 3).join(", ")} + ${brandNames.length - 3} more`;
      if (brandGroups.length <= 3) {
        return brandGroups.map((item, i) => {
          return (
            <div key={i}>
              <SelectionLabel>
                {item}
                <ClearIcon
                  className="fa fa-times"
                  data-name={item}
                  onClick={handleBrandClick}
                />
              </SelectionLabel>
            </div>
          );
        });
      }
      return (
        <SelectionLabel>
          {ThreePlusBrands}
          <ClearIcon className="fa fa-times" onClick={onClearBrands} />
        </SelectionLabel>
      );
    };

Example 4: loop with react and react native

import React from 'react';
import './App.css';


let items=['Item 1','Item 2','Item 3','Item 4','Item 5'];
let itemList=[];
items.forEach((item,index)=>{
  itemList.push( <li key={index}>{item}</li>)
})
function App() {
  
  return (
    <>
   
      <h2>This is a simple list of items</h2>
      <ul>
        {itemList}
      </ul>
    </>
  );
}

export default App;

Example 5: react render for loop

// for loop workaround in react render
[...Array(n)].map((_, index) => <span key={index}>element {index}</span>)

Example 6: react loop through array

this.items = this.state.cart.map((item, key) =>    <li key={item.id}>{item.name}</li>);