Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading