StillDead StillDead - 2 months ago 18
Javascript Question

How to repeat an element n times using JSX

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

Here you go:

let card = [];
_.times(8, () => {
  card.push(<span className="busterCards">♦</span>);
});

You may want to add key to each span element so React won't complain about missing the key attribute:

let card = [];
_.times(8, (i) => {
  card.push(<span className="busterCards" key={i}>♦</span>);
});

For more info about .times, refer here: https://lodash.com/docs#times