165

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

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?

6
  • 5
    How about new Array(8).join('<span className="busterCards">♦</span>');?
    – Ram
    Dec 9, 2015 at 21:39
  • 1
    The solution that @Vohuman suggested is a very clean way to get the job done. There is no comparable function defined within the lodash docs.
    – dbeg
    Dec 9, 2015 at 21:42
  • 2
    @Vohuman it would generate a String, while OP wants to create DOM using JSX syntax.
    – pawel
    Dec 9, 2015 at 21:45
  • 1
    @Vohuman it is weird but I am getting rendered the whole string
    – StillDead
    Dec 9, 2015 at 21:47
  • 1
    @pawel you are right, do you know how can I do it ?
    – StillDead
    Dec 9, 2015 at 21:48

12 Answers 12

483

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>)
9
  • 14
    Awesome answer for non-lodash users! Worth pointing out that it does require ES6 features (though I think it's implied by using let in the question anyway). Oct 14, 2016 at 2:09
  • 7
    For those using Typescript 2+, this will compile into Array(3).slice().map(...) which doesn't achieve the same result. See @Jian's answer below as a replacement. Jan 29, 2018 at 14:23
  • 1
    Nice, see my answer which elaborates more
    – vsync
    Jul 16, 2018 at 11:15
  • 5
    Why can't this just be Array(n).map((e, i) => <span className="busterCards" key={i}>♦</span>)
    – Kevin Wang
    Jun 4, 2019 at 21:30
  • 13
    @KevinWang because your suggestion will create an empty array with a length of 8, rather than an array consisting of 8 undefined items. Iteration won't work on the former. Chuck it in the console to see the difference.
    – Darbio
    Jun 13, 2019 at 23:04
63

solution without lodash or ES6 spread syntax:

Array.apply(null, { length: 10 }).map((e, i) => (
  <span className="busterCards" key={i}>
    ♦
  </span>
));
3
  • This seems more clean, but with more iterations than around 126000 I'm getting "Maximum call stack size exceeded" (at least in Chrome web desktop)
    – jave.web
    Feb 26, 2022 at 22:56
  • I came across a coworker using this code, and using Array.apply to loop a specific number of times was not intuitive to me at first glance. I'd personally consider other more intuitive solutions first if future devs will read your code. Apr 11, 2022 at 17:02
  • I am sorry to hear about that. The solution aims to use as less dependencies as possible. I would suggest your coworker improving the readability by making it a reusable function with sensible name like times. Apr 12, 2022 at 4:22
44

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

3
  • 2
    I am trying to assign this to the let card, but it is not repeating the element
    – StillDead
    Dec 9, 2015 at 21:54
  • 1
    Or simply const card = _(8).times(idx => <span key=${idx} className="busterCards">♦</span>);
    – tokland
    Oct 20, 2018 at 10:46
  • 1
    You can also simply return _.times(.....) to render the elements. Make sure you also use return (<Element></Element) inside too.
    – msqar
    Jul 10, 2019 at 0:19
25

Implementing this without Lodash

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

1
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Jun 18, 2021 at 8:42
8

I'm using this and works for me.

[...Array(10)].map((elementInArray, index) => ( 
    <div key={index}>
      Text in Loop
    </div>
))
7

Using _.times: https://jsfiddle.net/v1baqwxv/

var Cards = React.createClass({
    render() {
        return <div>cards {
          _.times( this.props.count, () => <span>♦</span> )
        }</div>;
    }
});
6

You could do it like this (without lodash):

var numberOfCards = 8; // or more.

if (data.hand >= numberOfCards) {
    var cards = [];

    for (var i = 0; i < numberOfCards; i++) {
        cards[i] = (<span className="busterCards">♦</span>);
    }
}
3

Straight forward options ways to do that without any external libraries (2021):

// straight forward but without key index. Not so good for react but work fine with worning 
Array(X).fill(<span className="busterCards">♦</span>)
// with index
Array(X).fill().map((v,i)=> <span className="busterCards">♦</span>)
Array.from( Array(X), (v,i) => <span key={i} className="busterCards">♦</span> )
// same thing basically 
Array.from( {length:X}, (v,i) => <span key={i} className="busterCards">♦</span> )
[...Array(3)].map( (_,i)=> <span key={i} className="busterCards">♦</span> )
2

You can create an array with as many items as you need rendered and then map through the array to render the correct number of elements you need.

const totalItems = 8;

const items = new Array(totalItems).fill(null);


// .... then
return (
    {items.map((_, idx) => <span className="busterCards" key = {idx}>♦</span>)}
);
0

You can use Lodash range.

_.range(20).map((_n, i) => <MyComponent key={i}/>)
0

So I was doing this today and came to this question and i think better approach is without creating an array and without any package. Which is recursion


const YourComp = ({ n }) => {
  if (n == 0) {
    return null;
  }
  return (
    <div className="py-8">
     do something
      <YourComp n={n - 1} />
    </div>
  );
};

cool?

-1

I thought, that if someone would like to use it in many places in the code, it would be a good idea to make it an npm package: https://www.npmjs.com/package/repeat-component. I think it will help someone :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.