-3

I am wondering if there is a neat way with ES6 to loop trough a given number of times, without looping trough an array, since I just want to give the number of times the loop should go?

E.g. if I provide a prop that says I should have 5 rows in a table.

RMT
  • 942
  • 2
  • 12
  • 32
  • 1
    I think the answer is even simpler: for(let i = 0; i < n; i++){/*Your code here*/} – Emil Karlsson Sep 16 '21 at 09:48
  • I do not think the ordinary for-loop looks as neat as the functions given by ES6. I originally thought I chould just make an "empty array" and loop trough it with an ES6 forEach, but I was hoping to find something that did not make me make a "mock array" – RMT Sep 16 '21 at 09:52
  • And I don't think that trying to "simulate" an array only to be able to call `.forEach` on it is neat at all. It's roundabout and [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) at best. – VLAZ Sep 16 '21 at 09:54
  • What is neater than writing your own abstraction? `repeat(5, i => { ... })`. – Felix Kling Sep 16 '21 at 14:55

1 Answers1

0

I made my own React component based on one what @Bhojendra Rauniyar said. "Mocking" an array and looping through it:

const Repeat = ({ numberOfTimes = 0, children }) =>
  [...Array(numberOfTimes)].map(() => children);

const ComponentThatUsesRepeat =  () => (
  <Repeat numberOfTimes={5}>
    <h1>My repeated content</h1>
  </Repeat>
);
RMT
  • 942
  • 2
  • 12
  • 32