How to repeat an element n times using JSX

StillDead picture StillDead · Dec 9, 2015 · Viewed 51.8k times · Source

I am using React/JSX in my app in order to accomplish what I want, also, Lodash.

I need to repeat an element a certain amount of times depending on a condition. How should I do that?

Here is the element:

<span className="busterCards">♦</span>;

And I am assigning it like this:

let card;
if (data.hand === '8 or more cards') {
  card = <span className='busterCards'>♦</span>;
}

So in this case, I need to repeat the element 8 times. What should be the process using Lodash?

Answer

Waiski picture Waiski · Sep 11, 2016

The shortest way to do this without any external libraries:

const n = 8; // Or something else

[...Array(n)].map((e, i) => <span className="busterCards" key={i}>♦</span>)