A
A
alex4answ2020-06-03 22:13:46
React
alex4answ, 2020-06-03 22:13:46

How to output N components?

Good afternoon, I need to display 5 identical components, how to do this?

Now I do this:

const count = 5; // передается в props
const items = Array(count).fill(1).map( (item, index) => <MyComponent key={`_${index}`} /> );


Of course it could be like this:
Like this

const count = 5;
const items = [];

for(let i = 0; i < count; i++) {
  items.push(<MyComponent key={`_${i} />);
}


There is no +- difference, but I use my own version so as not to inflate the size of the component, because it's all in the condition.

What options are there besides these 2, maybe using completely darkness, and should it be done differently?

I don't really like my version because of the complexity, so many steps to just fill the array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-06-03
@alex4answ

The shortest syntax is

const length= 5; // передается в props
Array.from({ length }, (_, index) => <MyComponent key={`_${index}`} /> );

but in general it is enough to create a function once in some utils and use it or use range from the lodash library

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question