Image scroll in image gallary using map

I tried using Index but it didn’t work. I gave an onclick function to both left and right and gave it each one a sepearte function. But I don’t know what to write in map function.

function goLeft(index) {
imagesRendered.map((item, index){

}

Hello Meet,
You can refer to below code to show single image at a time from images array:-

import { useState } from "react";
function imageGallery() {
  const [imageIndex, updateImageIndex] = useState(0);
  const imagesArray = [
    {
      url: "image-url",
    },
    { url: "image-url" },
  ];
  return (
    <div>
      <img src={imagesArray[imageIndex].url} />
      <button onClick={updateImageIndex(imageIndex - 1)}>Previous</button>
      <button onClick={updateImageIndex(imageIndex + 1)}>Next</button>
    </div>
  );
}

We don’t need map function when we are cycling between different images. Also there are some additional checks which would be required in the above code like not letting the imageIndex value go below 0 or above the length of images array.

1 Like