Categories
React Answers

How to Repeat an Element n Times with React?

Spread the love

Sometimes, we want to repeat an element n times with React.

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

Repeat an Element n Times with React

To repeat an element n times with React, we can use the Array function with the map array method.

For instance, we can write:

import React from "react";

const n = 8;

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

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.

Next, we call map to return span elements in the callback to render the spans.

We should set the key prop to a unique value so that React can keep track of all the elements.

Conclusion

To repeat an element n times with React, we can use the Array function with the map array method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *