Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Images and Performance

Dynamic Images with GatsbyImage and GraphQL

Load images from files, Markdown front matter or a CMS with gatsbyImageData queries, getImage and the GatsbyImage component, plus art direction.

StaticImage is perfect when the picture is fixed in the code. But a blog has a different cover image for every post, and a product page shows whatever the catalog says. In those cases the image path comes from data, so you use the other half of the image plugin: a GraphQL field called gatsbyImageData plus the GatsbyImage component.

The flow has three steps: make the file known to Gatsby (a source plugin), let the sharp transformer turn it into an image node, then query it and render it. The data layer itself is covered in the chapter on GraphQL; here we focus on the images.

Step 1: put the files in the data layer

gatsby-source-filesystem reads a folder and creates a File node for each file. Images get a childImageSharp child node, created by gatsby-transformer-sharp.

JavaScript
// gatsby-config.js (real Gatsby, read-only)
module.exports = {
  plugins: [
    "gatsby-plugin-image",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    { resolve: "gatsby-source-filesystem", options: { name: "images", path: `${__dirname}/src/images` } },
    { resolve: "gatsby-source-filesystem", options: { name: "posts", path: `${__dirname}/content/posts` } },
  ],
}

Step 2: query gatsbyImageData

In a page query you ask for the image node and call gatsbyImageData with the options you would otherwise give StaticImage as props:

JSX
// src/pages/blog.js (real Gatsby, read-only)
import * as React from "react"
import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"

export default function Blog({ data }) {
  return (
    <ul>
      {data.allMarkdownRemark.nodes.map((post) => {
        const cover = getImage(post.frontmatter.cover)
        return (
          <li key={post.id}>
            {cover && <GatsbyImage image={cover} alt={post.frontmatter.coverAlt} />}
            <h2>{post.frontmatter.title}</h2>
          </li>
        )
      })}
    </ul>
  )
}

export const query = graphql`
  query BlogCovers {
    allMarkdownRemark(sort: { frontmatter: { date: DESC } }) {
      nodes {
        id
        frontmatter {
          title
          coverAlt
          cover {
            childImageSharp {
              gatsbyImageData(width: 640, placeholder: BLURRED, formats: [AUTO, WEBP, AVIF])
            }
          }
        }
      }
    }
  }
`

In the front matter of a post, cover: ./cover.jpg is a path relative to the Markdown file. Gatsby links it to the image File node automatically, which is why cover { childImageSharp { ... } } works. Note that in GraphQL the enum values are written in capitals (BLURRED, WEBP), while the StaticImage props use lowercase strings.

getImage, getSrc and friends

The object returned by the query is nested. getImage(node) digs out childImageSharp.gatsbyImageData (or gatsbyImageData directly) and returns undefined when there is no image, so your code can skip it. getSrc(node) returns a plain URL, handy for Open Graph tags. Always handle the missing case: a post without a cover would crash GatsbyImage with a missing prop.

The next stand-in implements the same idea with plain objects.

JS Stand-in: a getImage helper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rendering props of GatsbyImage

GatsbyImage takes image (the data), alt, and styling props such as className, imgClassName, style, objectFit and objectPosition. loading can be lazy or eager. The wrapper element holds the aspect ratio, so give the wrapper the size classes and let objectFit="cover" fill it.

Images from other sources

Images are not limited to local files. A CMS source plugin (such as Contentful or Sanity) often exposes a gatsbyImageData field on its asset type directly, so no sharp step is needed. For any remote URL you can use gatsby-plugin-image's GatsbyImage with a node created by createRemoteFileNode (from gatsby-source-filesystem) during onCreateNode, which downloads the file and makes it a File node, ready for childImageSharp.

Art direction

Sometimes a phone should show a tall crop and a desktop a wide one, which srcset alone cannot do. withArtDirection takes a default image and a list of { media, image } pairs and returns image data for GatsbyImage:

JSX
// read-only
import { GatsbyImage, getImage, withArtDirection } from "gatsby-plugin-image"

const images = withArtDirection(getImage(data.desktop), [
  { media: "(max-width: 700px)", image: getImage(data.mobile) },
])
// <GatsbyImage image={images} alt="Storefront" />

Under the hood it writes several <source media="..."> elements inside <picture>.

A decision helper

This stand-in picks between the two components with the rule you just learned.

JS Stand-in: StaticImage or GatsbyImage?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which package turns a File node into an image node with gatsbyImageData?

    The sharp transformer creates the childImageSharp child node that exposes gatsbyImageData.
  2. 2. Why use getImage(node) instead of reading the nested field yourself?

    getImage unwraps the data and tolerates missing values, so you can skip the component.
  3. 3. How are enum options written in a gatsbyImageData GraphQL query?

    GraphQL enums are unquoted capitals; StaticImage props use lowercase strings.
  4. 4. What does withArtDirection do?

    It produces picture sources with media conditions so each viewport gets its own crop.

Summary

  • Use gatsbyImageData queries plus GatsbyImage when the image comes from data.
  • gatsby-source-filesystem and gatsby-transformer-sharp turn files into queryable image nodes.
  • getImage unwraps nested data and returns undefined for missing images; always check it.
  • Relative paths in front matter link to file nodes automatically.
  • withArtDirection swaps crops per media query.

Next: Formats, layouts and placeholders