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.
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) => {
...
})