Search code examples
reactjsgraphqlgatsbygatsby-image

Gatsby graphql query for GatsbyImage to use a local image from project


I'd just like to use an image using GatsbyImage component.

Normally you do it using <img src='./img.jpg'/>. How is it done with GatsbyImage, so i can send an image using props.


Solution

  • If you want to use GatsbyImage you need to provide extra GraphQL node data that Gatsby infers using its transformers and sharps. To do so, you need to tell Gatsby where those images are, in your case, by setting the following snippet in the gatsby-config.js:

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

    Note: you can have many instances of the gatsby-source-filesystem

    After starting the gatsby develop again to refresh the sources, you will see the node available in the GrahiQL playground (localhost:8000/___graphql) where you should test your query but it should look like:

      image: file(relativePath: {eq: "free-time.jpg"}) {
        childImageSharp {
          gatsbyImageData
        }
      }
    

    Tested in your CodeSandbox and working.