Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Images in front matter for Gatsby.js

I've been struggling with this:

My front matter looks like:

---
path: '/path-to/'
title: 'Title of Post'
indexImage: './img.jpg'
---

with my image in the same folder as my index.md file.

In my templates/post.js file, I have the following line:

<img src={ post.frontmatter.indexImage }></img>

thinking this would pull in the source listed in the front matter. My post.js query is:

export const postQuery = graphql`
  query BlogPostByPath($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        path
        title
        indexImage
      }
    }
  }
`;

Below is the error message:

GraphQL Error Field "indexImage" of type "File" must have a selection of subfields. Did you mean "indexImage { ... }"?

Any thoughts on why this isn't working? I'm still new to Gatsby, so it may be an issue that is over my head. Thanks in advance.

like image 432
Dylan Stratton Avatar asked Oct 12 '17 16:10

Dylan Stratton


People also ask

How does Gatsby use local images?

If you are using a local image, copy it into the project. A folder such as src/images is a good choice. Add the StaticImage component to your template.

Does Gatsby use markdown?

Gatsby can generate static pages from almost any data source, such as a Content Management System (CMS), API, database, or even a local file system. Markdown files are a popular file-based source to use with Gatsby.

How do you embed a video in The Great Gatsby?

The easiest method for including video on a Gatsby site is to source an uploaded file from a site like YouTube, Vimeo, or Twitch. Using the source URL from one of those hosts, you can use Remark plugins or create a custom <iframe> solution to embed videos into your Gatsby site.


2 Answers

must have a selection of subfields. Did you mean "indexImage { ... }

Is the key part of the error.

Anytime you see "subfields" and a field (like indexImage) with { ... } it means that this is an "object" type not a "scalar" (e.g. string, number, float, etc.) type.

So your query should look something like:

query BlogPostByPath($path: String!) {
  markdownRemark(frontmatter: { path: { eq: $path } }) {
    html
    frontmatter {
      path
      title
      indexImage {
        childImageSharp {
          resolutions(width: 400) {
            width
            height
            src
            srcSet
          }
        }
      }
    }
  }
}

This example site documents how to use the image processing queries https://image-processing.gatsbyjs.org/

like image 144
Kyle Mathews Avatar answered Oct 02 '22 18:10

Kyle Mathews


Invalidate the build cache by deleting the .cache folder.

like image 32
Scriptonomy Avatar answered Oct 02 '22 20:10

Scriptonomy