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
Answers
It is not good practice to put the index in key, as react’s document says:
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.
In my opinion it would be better to map over you pictures
Array
if it’s possible, especially if those pictures have anid
which you could use as akey
inside your loop instead of theindex
.In all cases you can use an underscore if you don’t need to use the first param to avoid the warning.