How to Repeat an Element n Times Using JSX?

Sometimes, we want to repeat an element n times using JSX.

In this article, we’ll look at how to repeat an element n times using JSX.

Repeat an Element n Times Using JSX

To repeat an element n times using JSX, we can create an array with n empty slots with the Array constructor.

Then we call map to map that into the element we want to display.

For instance, we write:

import React from "react";

const n = 8;

export default function App() {
  return (
    <>
      {[...Array(n)].map((e, i) => (
        <span className="diamond" key={i}>
          ♦
        </span>
      ))}
    </>
  );
}

to repeat the diamond character 8 times.

We set n to 8.

Then we pass that in as the argument of Array to create an array with 8 empty slots.

Next, we spread that into an array to return an array with 8 undefined entries.

Finally, we call map with a callback that returns a span with the diamond in it.

Conclusion

To repeat an element n times using JSX, we can create an array with n empty slots with the Array constructor.

Then we call map to map that into the element we want to display.