4

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.

Rastislav Uhrin
  • 150
  • 1
  • 7
  • What's the output? What's the error? Do you have `img` data in the `ChildComp`? Is the `useStaticQuery` fetching the proper data? – Ferran Buireu Dec 22 '21 at 14:20
  • `data` is `null`?If so, this is where the issue is... Well, try to provide a Sandbox or similar, it's impossible to guess what's wrong in your structure with dummy data that is not showing the code structure (`data.something` is not present in the query, etc) – Ferran Buireu Dec 22 '21 at 15:38
  • yup, so i added the link to the question – Rastislav Uhrin Dec 22 '21 at 16:29

2 Answers2

5

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.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
-1

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} />
Rastislav Uhrin
  • 150
  • 1
  • 7