To repeat an element n times with React, we can use the Array function with the map array method. to create an array with 8 span elements with the same content by calling the Array with the n to create an empty array with n slots. Then we use the spread operator to make a copy of it.
To loop through an array of objects in React:Use the map() method to iterate over the array. The function you pass to map() gets called for each element in the array. The method returns a new array with the results of the passed in function.
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:
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]]
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>)}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With