PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, June 30, 2022

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

 June 30, 2022     arrays, gatsby, javascript, reactjs, shopify     No comments   

Issue

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



Answered By - Ian Rios
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing