0

I'm trying to render a certain number of divs based on the pageCount value I have in my app. My approach is as follows

render() {
  const { pageCount } = this.props;
  function renderPages() {
    for (let i = 0; i < pageCount; i++) {
      return <div>{i}</div>;
    }
  }
  return <div style={{ textAlign: "center" }}>{renderPages()}</div>;
}

So here pageCount value i get is 5. I want to render 5 divs but when returning, the loop breaks. How can I fix this?

keikai
  • 14,085
  • 9
  • 49
  • 68
CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • Does this answer your question? [How to repeat an element n times using JSX](https://stackoverflow.com/questions/34189370/how-to-repeat-an-element-n-times-using-jsx) – Agney Mar 02 '20 at 06:42

2 Answers2

3

As you noticed, your loop is breaking early due to the return. Instead, you can render an array of JSX. One way could be to create an array in your renderPages and .push() your <div>s into that:

function renderPages() {
  const divs = [];
  for (let i = 0; i < pageCount; i++){
    divs.push(<div>{i}</div>);
  }
  return divs;
}

return (
  <div style={{textAlign:'center'}}>
    {renderPages()}
  </div>
)

Or, you can populate an array using Array.from() with a mapping function:

function renderPages() {
  return Array.from({length: pageCount}, (_, i) => <div>{i}</div>);
}

return (
  <div style={{textAlign:'center'}}>
    {renderPages()}
  </div>
)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Returning inside the for loop always breaks the loop. So instead you can use .map Read more about it here

render(){
    const {pageCount} = this.props;
    function renderPages(){
        return new Array(pageCount).map((item, index) => (
            <div>{item}</div>
        ));
    }
    return (
        <div style={{textAlign:'center'}}>
            {renderPages()}
        </div>
    )
}
void
  • 36,090
  • 8
  • 62
  • 107