Marios T.
Marios T.

Reputation: 11

How do I use gatsby-image with an Array of Objects?

How do I use gatsby-image with an Array of Objects?

For example I have this:

const dataImgs = [
  { id: 1, title: "Astronaut", img: "gatsby-astronaut.png" },
  { id: 2, title: "Icon", img: "gatsby-icon.png" }
]

And the files are in the folder /src/images

And I want to use use Gatsby Image for Optimization

My problem is I do not understand how I can make a GraphQL query. I'm getting the filename from an object and I want to join the paths in the GraphQL Query.

Thanks.

Here's a codesandbox which may help you understand better what i'm tring to do https://codesandbox.io/s/summer-hooks-im9q7?file=/src/components/image.js

Upvotes: 0

Views: 1497

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29335

There's a lot of implementation here. I will try to explain it step by step.

You need to provide a certain amount of data to use gatsby-image and then loop through it.

First of all, you need to set up your Gatsby filesystem by adding (in your gatsby-config.js):

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/assets/images`,
  },
},

Note: you may need to install the plugin. More information here.

This will make your image queryable by GraphQL and extend all gatsby-image potential to them.

The next step is to query the images and retrieve all the needed information using the GraphQL fragment you've provided. That query is relative to your project structure, but should look something like this:

{
  allImageSharp {
    edges {
      node {
        fluid(maxWidth: 800) {
          aspectRatio
          src
          srcSet
          sizes
          originalImg
          originalName
        }
      }
    }
  }
}

Note that this equals to use a fragment:

{
  allImageSharp {
    edges {
      node {
        fluid(maxWidth: 800) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

The final step is to loop through your object, which in any page/component should be stored inside props.data. Something like:

const yourComponent= ({ data }) => {

  return <Layout>
    {data.edges.map(({ node })=> <Img fluid={node.childImageSharp.fluid} />)}
  </Layout>;
};

export default yourComponent;

export const yourComponentData= graphql`
    query getArticleInformation  {
     allImageSharp {
        edges {
          node {
            fluid(maxWidth: 800) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }    
    }
`;

The looped object internal structure may differ a lot depending on your retrieved values but the idea is this.

Upvotes: 3

Related Questions