Skip to content
Advertisement

Pass onClick to each image using map function

I am looking to pass an onClick function to each image element created using the map function. So that when a user clicks the thumbnail image it changes the main image to the thumbnail that was clicked.

Right now however it seems like the onClick function is being called without even being clicked and the image that is displayed is the last image in the array.

Also when I click the images nothing happens.

I feel like there may be multiple issues but not sure what.

let currentIndex = 0;

let changeImage = function(index) {
  currentIndex = index;
}

const gallery = 
  product.images.length > 1 ? (
    <Grid gap={2} columns={5}>
      {product.images.map((img, index) => (
        <GatsbyImage 
          image={img.gatsbyImageData}
          key={img.id}
          alt={product.title}
          index={index}
          onclick={changeImage(index)}
        />
      ))}
    </Grid>
  ) : null;

The above code is affecting the below code.

<div>
 {console.log('index is: ' + currentIndex)}
 <GatsbyImage
   image={product.images[currentIndex].gatsbyImageData}
   alt={product.title}
 />
 {gallery}
</div>

Advertisement

Answer

add the arrow function to the syntax like this , change onclick={changeImage(index)}

to this onclick={()=>changeImage(index)}

and for the rerendering .

i think you need to use state instead of let change let currentIndex = 0; to const [currentIndex,setCurrentindex]=useState(0) and currentIndex = index; to setCurrentindex(index) we use State to rerender the dom whenever there is a change , in your case the dom is not rerendering because you are not using state . that should solve your problem

Advertisement