Using .map with numbers not an array, or ignoring the first parameter in a map and just using index

56 Views Asked by At

I am making a react app and I was trying to do a map to loop over and display multiple images. I was trying to make this dynamic so that if the number of images is different in each folder it will display the appropriate amount of images.

<div className="rotating-gallery-image-container" style={{transform: currentTransform} as React.CSSProperties}>
   {[...Array(numberOfPictures)].map((x, index) =>
       <span style={{ "--i": index } as React.CSSProperties} key={index}>
          <img
              src={`/images/gallery-images/${imageGroup}/${index}.jpg`}
          />
       </span>
    )}
</div>

I'm only used to mapping over arrays, but in this case numberOfPictures is just a number. Is there a better way for mapping over this or doing a foreach?

Also the only way to get the index is to have it as the second parameter but then I don't have any use for the "x" in this situation. I end up with the warning that x is declared but its value is never read, which I would want to get rid of.

Is there a way to just have the index and no first parameter in the map? Or a better way to render multiple times based on a number.

2

There are 2 best solutions below

1
J.dev On BEST ANSWER

In my opinion it would be better to map over you pictures Array if it's possible, especially if those pictures have an id which you could use as a key inside your loop instead of the index.

In all cases you can use an underscore if you don't need to use the first param to avoid the warning.

[...Array(numberOfPictures)].map((_, index) => {
    ...
})
1
Masoud Hasanzadeh On

It is not good practice to put the index in key, as react's document says:

You might be tempted to use an item’s index in the array as its key. In fact, that’s what React will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.

The best approach is, using a unique id from the data you are trying to map over, then you'll have to use the x and you don't get the mentioned error.