Skip to content Skip to sidebar Skip to footer

Mapping Array Of Images Leads To The Same Image Repeating On Every Instance

Im trying to map an object from an array of arrayed images into an image gallery on separate product pages (coming from strapi). The correct number of images appear but it repeats

Solution 1:

You are not setting properly the key value. image is the iterable object, is just a way of naming each index of your galleryImage so the id, doesn't stand as the id of the image itself.

Change it to:

<div className="image-grid">
  {data.home.galleryImage.map((image) => (
     <Imagefluid={image.formats.medium.childImageSharp.fluid}alt="hh"key={image.id}class="galleryimg"thumbnail/>  
   ))}
</div>

To access the nested image properties, you need to access its child properties, like the way you do in image.formats, accessing to formats position, but using image.id.

For further details, you can check the MDN docs.

In addition, if the loop is printing the same image, internally the id is not correctly set from GraphQL when created the data node from Strapi. You can customize the GraphQL node schema to add custom parameters in order to bypass this limitation using different APIs provided by Gatsby, createRemoteFileNode should fit your requirements.

const { createRemoteFileNode } = require(`gatsby-source-filesystem`);
    
    exports.onCreateNode = async ({ node, actions, store, cache }) => {
      const { createNode, createNodeField } = actions;
    
      if (node.internal.type !== null && node.internal.type === "StrapiPortfolio") {
        for (const category of node.category) {
          for (const image of category.images) {
            console.log(image);
            const fileNode = awaitcreateRemoteFileNode({
              url: "http://localhost:1337" + image.url,
              store,
              cache,
              createNode,
              createNodeId: (id) => image.id.toString(),
            });
    
            if (fileNode) {
              image.localFile___NODE = fileNode.id;
            }
          }
        }
      }
    };

Source: How to query multiple images in Gatsby from Strapi using Graphql

Depending on your data structure, you may need to change the loop and some other parameters. In this case, images are inside a category node so, it has to be inferred by nesting two different loops.

The idea is to loop through all your image nodes and add the localFile___NODE field with:

image.localFile___NODE = fileNode.id;

The id is previously created in:

createNodeId: (id) => image.id.toString(),

Post a Comment for "Mapping Array Of Images Leads To The Same Image Repeating On Every Instance"