close

How to repeat an element n times using JSX

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to repeat an element n times using JSX in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to repeat an element n times using JSX ?

  1. How to repeat an element n times using JSX ?

    repeat an element n times using JSX

  2. repeat an element n times using JSX

Method 1

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

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

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment