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

Viewed 284

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.

2 Answers

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.

After npm init gatsby, 'src/images' folder is created and this is the basic root of the relative path which is set by default in gatsby.config.js

{
         resolve: 'gatsby-source-filesystem',
         options: {
            name: 'images',
            path: `./src/images/`,
         }
}

So put your img.jpg to images folder and query by using relative path

   const data = useStaticQuery(graphql`
  {
     file(relativePath: { eq: "free-time.jpg" }) {
        childImageSharp {
           gatsbyImageData
        }
     }
  }
`);

and insert it to GatsbyImage

 const img = getImage(data.file);

 <GatsbyImage image={img} />
Related