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?

1
  • Ah right, good approach. I was thinking of that I wasn't sure whether or not it'd be the best solution :) Commented Oct 18, 2018 at 8:54

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, going to tweak you answer to match my problem better but this worked more reliably for me than the other solutions posted!
@BarryMichaelDoyle glad it helps!
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>
  );
}

1 Comment

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.
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>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.