0

I try to for loop numbers of components, but it seem didn't work. I setState the totalitem to 5, and the output components only have 1.

_renderSomeItems(){
  for(var i = 0; i < this.state.totalitem; i++){
    return(
      <SpecialItem key={i} />
    );
  }      
}
FeelRightz
  • 2,777
  • 2
  • 38
  • 73
  • 1
    Possible duplicate of [Does return stop a loop?](https://stackoverflow.com/questions/11714503/does-return-stop-a-loop) – bennygenel Oct 16 '17 at 07:53

2 Answers2

1

return inside a for loop will end the loop. You should use Array.prototype.map(). Don't forget to return result of map.

_renderSomeItems(){
  // considering this.state.totalitem is to be an array
  return this.state.totalitem.map((item, index) => {
    return(
      <SpecialItem key={index} />
    );
  }      
}

// or

_renderSomeItems(){
  const results = [];
  for(var i = 0; i < this.state.totalitem; i++){
    results.push(<SpecialItem key={i} />);
  }
  return results;
}
bennygenel
  • 23,896
  • 6
  • 65
  • 78
0

Using lodash

import _ from 'lodash'

_renderSomeItems(){
  return _.range(this.state.totalitem).map(item, index) => (
    <SpecialItem key={i} />
  );
}
klugjo
  • 19,422
  • 8
  • 57
  • 75