jrock2004
jrock2004

Reputation: 3501

Gatsby Image Not Found

So I am messing around with creating a markdown blog and for some reason I cannot get images to work.

Gatsby-config.js

plugins: [
    'gatsby-plugin-image',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: `${__dirname}/src/images/`,
      },
      __key: 'images',
    },
]

Images are stored in src/images

blogpost.md

---
title: New Provider
image: ../images/new-provider.jpg
imageMeta:
  attribution:
  attributionLink:
featured: false
---

Here is how I am querying the data

export const query = graphql`
  query PostsByID($slug: String!) {
    mdx(slug: { eq: $slug }) {
      body
      frontmatter {
        title
        authors
        date
        featured
        image
        tags
      }
    }
  }
`;

And here is my img element

<Img alt={title} fluid={image} key={title} />

// I tried this too
<img alt={title} src={image} />

When the page loads , I just see my alt text and in the console I see http://localhost:8000/images/new-provider.jpg

Upvotes: 0

Views: 1165

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29335

To query an image, you need the childImageSharp data (fetched from Gatsby's sharps and transformers, you have them both installed).

If the data structure and paths are properly set, your GraphQL query should look like:

export const query = graphql`
  query PostsByID($slug: String!) {
    mdx(slug: { eq: $slug }) {
      body
      frontmatter {
        title
        authors
        date
        featured
        image {
          childImageSharp {
            fluid(width: 125, height: 125) {
              ...GatsbyImageSharpFluid
            }
          }
        }
        tags
      }
    }
  }
`;

There you have the proper nodes and properties that Gatsby image have to render your image. Then you can use:

<Img alt={title} fluid={image.childImageSharp.fluid} key={title} />

If your GraphQL query is not able to fetch childImageSharp node (test it in the GraphiQL playground at localhost:8000/___graphql) check the relativity of the markdown paths.

Upvotes: 1

Related Questions