Search code examples
javascriptarraysreactjsshopifygatsby

How do I properly use the map function to get the index of the element in the array?


Hello I am trying to find the index of the element in an array using map so that eventually I can create a onClick function that will change the image based on that index.

However when I add index to my map function I then get an error stating that the img is not defined.

const currentIndex = 0;

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}
        />
      ))}
    </Grid>
  ) : null; 

The above code displays a list of thumbnail size images. I would like to eventually be able to click on each image and have the larger image appear.

Code for the larger image is below.

<div>
  <GatsbyImage
    image={product.images[currentIndex].gatsbyImageData}
    alt={product.title}
  />
  {gallery}
</div>

Solution

  • Simple parenthesis fix:

    const currentIndex = 0;
    
    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}
            />
          ))}
        </Grid>
      ) : null; 
    

    Make sure to not pass two values, but one value to Array.map: a function with its own optional parameter called 'index'

    Consider expanding your work to a function that you can just reference, to make life easier, and code more legible, like this:

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

    See more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#syntax