1

I'm familair with mapping through and array to render something for each number in an array. But what is an effective way to accomplish the same thing using a number.

I've found myself in a situation where I have an integer representing number of pages and a component <Page> which takes the prop pageNumber.

I've got the following render function in place:

renderPages() {
  for (let i = 1; i < this.state.numPages; i++) {
    return <Page pageNumber={1} />;
  }
}

The renderPages function is implemented as follows in my class render function:

render() {
  return (
    <div>
      {this.renderPages()}
    </div>
  );
}

I understand that once the first return occures the renderPages is exited. So in the end it only renders the first page. How can I render more pages here?

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143

3 Answers3

1

Append to an array and then return the array.

renderPages() {
    const arr = []
  for (let i = 1; i <-this.state.numPages; i++) {
    arr.push(<Page pageNumber={1} />)
  }
    return arr
}

or you can do this without using a function by creating an empty array,

render() {
  return (
    <div>
      {(new Array(this.state.numPages)).map((item, i)=><Page pageNumber={i} />)}
    </div>
  );
}
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
1
renderPages() {
    const arr = []
  for (let i = 1; i <-this.state.numPages; i++) {
    arr.push(<Page pageNumber={1} />)
  }
    return arr
}

render() {
  return (
    <div>
      {this.renderPages().map((item)=>(item))}
    </div>
  );
}
Roopak Puthenveettil
  • 1,387
  • 2
  • 13
  • 27
  • 1
    It might be a good idea to explain what this code does. Whilst it is useful to have the code, the OP (and everyone else) would benefit from an explanation. – JustCarty Oct 18 '18 at 09:53
1

Just another preferences (shorter version):

https://stackoverflow.com/a/51335795/9206753 (my previous answer)

To loop for a number of times and return, you can achieve it with the help of from and map:

  <div>
    {Array.from(Array(this.state.numPages)).map((item, index) =>
      <Page key={index} pageNumber={index + 1} />
    )}
  </div>

Hope it helps

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
Jee Mok
  • 6,157
  • 8
  • 47
  • 80