How to repeat an element n times using JSX and Loadsh

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?


Solution 1:

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>)

Solution 2:

solution without lodash or ES6 spread syntax:

Array.apply(null, { length: 10 }).map((e, i) => (
  <span className="busterCards" key={i}>
    ♦
  </span>
));

Solution 3:

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

Solution 4:

<section>
      {Array.from({ length: 10 }, (_, i) => <span key={i}>Your text</span>)}
 </section>

How does this work?

Array.from() is used in two contexts:

  1. Creating an array from an array-like data structure. For example, we can convert a map into an array using Array.from()

    const map = new Map([ [1, 2], [3, 4], [4, 5] ])

    console.log(Array.from(map)) //gives an array - [[1, 2], [3, 4], [4, 5]]

  2. Creating an array and filling out the values (This can be handy when we need to create an array containing more elements)

Array.from() accepts an object and a callback function.

Array.from({ length: 7 }, (() => 10)) // gives [10,10,10,10,10,10,10]

We can take advantage of the index (second parameter) inside the callback function to provide unique array elements

Array.from({ length: 4 }, ((_, i) => i + 1)) // [1,2,3,4]