Home > Software design >  Pass onClick to each image using map function
Pass onClick to each image using map function

Time:04-20

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>

CodePudding user response:

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

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

  • Related