DEV Community

Jamie Barton
Jamie Barton

Posted on

Using Gatsby Image with product images

The time has come to implement product images using Gatsby Image.

Since the beginning of the tutorial, there has been a new version of gatsby-source-chec.

Inside package.json, update the version of gatsby-source-chec to be at least 1.2.0, and run npm install.

Once installed, go ahead and install the dependencies for using Gatsby Image.

npm i -E gatsby-transformer-sharp gatsby-plugin-sharp gatsby-image
Enter fullscreen mode Exit fullscreen mode

Once installed, you will need to update the pageQuery in templates/ProductPage.js:

export const pageQuery = graphql`
  query ProductPageQuery($id: String!) {
    product: checProduct(id: { eq: $id }) {
      id
      name
      ...PriceInfo
      images {
        childImageSharp {
          fluid(maxWidth: 560) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

Here we're calling the GatsbyImageSharpFluid fragment for our product images. The images array is an array of File's added by the updated source plugin.

Inside templates/ProductPage.js, go ahead and import the Gatsby Image component:

import Img from "gatsby-image";
Enter fullscreen mode Exit fullscreen mode

Then inside the page function, you will want to destructure the first item from the product.images array, and call this mainImage:

const [mainImage] = product.images;
Enter fullscreen mode Exit fullscreen mode

Then all that's left to do is render the <Img /> component on the page with the applicable components if it exists.

{mainImage && (
  <Img
    fluid={mainImage.childImageSharp.fluid}
    style={{ maxWidth: "50%" }}
  />
)}
Enter fullscreen mode Exit fullscreen mode

Run it locally

That's it!

Now you're ready to go! Type npm run dev in your Terminal, and head to the local port to browse your Gatsby powered commerce site.

Discussion (0)