简体   繁体   中英

How to repeat an element n times using JSX and Lodash

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?

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 without lodash or ES6 spread syntax:

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

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

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

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

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

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

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

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

I'm using this and works for me.

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

您可以使用 Lodash range

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM