DEV Community

Cover image for An Introduction to Gatsby Plugin Image
Robert Marshall
Robert Marshall

Posted on • Originally published at robertmarshall.dev on

An Introduction to Gatsby Plugin Image

The Gatsby Image Plugin introduces a brand new (currently beta) way of handling and transforming images within Gatsby. Set as a replacement for the original Gatsby Image component, it introduces a cleaner way of using GraphQL queries as well as a brand new StaticImage component. Throw in a couple of helper functions and a nicer API, this set of components seems to be a great improvement!

This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/an-introduction-to-gatsby-plugin-image

Table of Contents

Original Gatsby Image Component

Gatsby Image is what we know as the original Gatsby component. It is a clever piece of code that works with the Gatsby GraphQL queries to easily generate optimized images. Under the hood it uses Gatsby Plugin Sharp to handle its image transformations. It was initially a great solution to the problem of having heavy images slowing down a website. No need to mess about with custom lazy load packages and every growing Gulp scripts, just drop in the component.

As the pressure for better, faster, and more efficient websites has increased, Gatsby have introduced a set of new and improved components, housed under the name Gatsby Plugin Image.

The Different between Gatsby Image and Gatsby Plugin Image

The newer Gatsby Plugin Image has taken the older Gatsby Image, completely refactored it and introduced some great new features. These differences include:

Named Import

We have been used to GatsbyImage being a default export, we could import it directly from the package. This has all changed due to the introduction of several other features. Now GatsbyImage is a named import.

import { GatsbyImage } from "gatsby-plugin-image"
Enter fullscreen mode Exit fullscreen mode

Not a gigantic change, but definitely something to remember when refactoring older components.

Static Image Component

The reason for the change in the way we import the GatsbyImage component seems to be partly due to this new addition. The StaticImage component.

It provides a clean way of importing a static image. This is particularly useful if the image required is never going to change on a particular template or within a component. An example of this could be an image on a 404 page, or the site logo. In the past all images, whether dynamic or static used the same component.

The benefit of this new StaticImage component is that it uses absolute and relative paths, rather than having to use gatsby-source-filesystem to find a local image. This is a far nicer developer experience!

There are restrictions on how this component can be used, for example the name of the file must be provided directly inside the component that the StaticImage component is used in. This is due to it being analysed on build, so unable to use props. However, this should not be seen as an issue as dynamic images can still be used with the GatsbyImage component.

How to use the Static Image Component

Change in Gatsby Image

There are a number of changes to the GatsbyImage component that you should probably be aware of before upgrading.

Gatsby Image has been updated to be a functional component. This means that it cannot be extended in the same way that could have been when it was a class based component. Now if you are wanting to reuse code across components, you should use Composition.

The ‘fluid’ image object no longer exists, and the data object created by the GraphQL query should not be altered as it could have been in the past. When using the getImage function (expanded on below) the data return can not be changed. This data is no longer seen as ‘public’, and the developers state that this could be changed without notice. Unfortunately this also means that custom art direction is not supported, although there is talk of this being added at a later date.

No More Fragments, New API

We do not need to type ...GatsbyImageSharpFixed any more. This has since been replaced with the GatsbyDataImage function. This function can take a range of arguments outlined in the gatsby-plugin-image documentation. In essence it is a far cleaner way to getting the same result, with a few new additions.

As well as the ability to use blur up base4 images, and SVG traced loaders, there is now a Dominant Colour setting. This calculates the dominate colour of the image and uses it as a solid background colour whilst the image is loading.

There is also a new image format: AVIF. Originally used in video, this royalty free format is currently supported in Chrome, soon to be added to Android and Firefox. This new file format is usually half the size (weight) of a WebP format. This is going to be a great help in creating faster websites!

To read more about AVIF take a look at this article.

Introduction of getImage and getSrc

These two new additions are a massive improvement over the original Gatsby Image plugin, and a real benefit to the developer experience.

GatsbyImage getImage()

The getImage function is an helper function used to make the code cleaner and easier to read. It accepts a ‘File’ that has been created in the GraphQL query, and returns an object to be passed into the Gatsby Image component. Gone are the days of having to comb through levels of nested objects to get to the ‘Fluid’ object.

Example of how to use GatsbyImage getImage

GatsbyImage getSrc()

I can see myself using this new helper function in a fair few places! It is used to return a particular images src URL. An example of how it could be used, would be providing absolute URLs to an SEO component. This was something I really struggled with when first getting to grips with Gatsby.

How to use Gatsby Image getSrc

Considerations

Before jumping in and using this new plugin/set of components on your site, there are few things to consider:

Possible Bugs

This component is still in its infancy, and although the Gatsby team and community are improving it at an incredible rate it may still have bugs. It is in beta after all!.

Using the Old with the New

Even if the Gatsby Image Plugin moves out of beta stage relatively quickly and is ready to be rolled out onto production sites, other packages may not be as quick to make the upgrade. An example of this could be that you are using a CMS that has not updated to the newer version of the API.

This is not a real issue, as both the older and new plugin can be used together on a site. This may be something to consider though as the JavaScript bundle size will be increased.

Changing APIs

As the component is in beta, although at a fairly stable point – there is always a chance that things change. If your site (or numerous sites) have a lot of areas where custom image sizes are used, it may well be worth holding off until the component is completely stable. If the amount of work to implement is small then you may not see a few changes as an issue. But this could add up across sites/image implementations.

How to Use StaticImage

The devs have done a great job in making an easy to use component. To add an image using StaticImage you simply:

import { StaticImage } from "gatsby-plugin-image"
export function YourWrapperComponent() {
  return <StaticImage src="../images/yourStaticPicture.png" alt="Incredible Art" />
}
Enter fullscreen mode Exit fullscreen mode

How To Use Gatsby Image

The GatsbyImage component is similar to the older implementation, but with a few tweaks. For example, you still need to create the GraphQL query, but now we use the GatsbyImageData function alongside the getImage helper function. Then this is passed into the GatsbyImage component:

import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
function BlogPost({ data }) {
  const image = getImage(data.blogPost.avatar)
  return (
    <section>
      <h2>{data.blogPost.title}</h2>
      <GatsbyImage image={image} alt={data.blogPost.author} />
      <p>{data.blogPost.body}</p>
    </section>
  )
}
export const postQuery = graphql`
  query {
    blogPost(id: { eq: $BlogId }) {
      title
      body
      author
      avatar {
        childImageSharp {
          gatsbyImageData(
            width: 400
            placeholder: BLURRED
            formats: [AUTO, WEBP, AVIF]
          )
        }
      }
    }
  }
`
Enter fullscreen mode Exit fullscreen mode

How To Use getSrc()

Much like the StaticImage component, this helper function is very easy to use. In this example the GraphQL query has been carried out in a parent component. The file has then been passed through as a prop and passed into the getSrc function. This function then returns the image src URL.

import { getSrc } from "gatsby-plugin-image"
const YourWebPage = ({ data }) => {
  const seoImagePath = getSrc(data.file)
  return (
    <>
      <SEO imageSrc={seoImagePath} />
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Your Thoughts

This new set of components look like they are going to be a great addition to Gatsby’s already solid collection. Although early days, they have some real potential.

I would love to know your thoughts on the above, and if you have had any successes/issues with the components. Please let me know at @robertmars

Top comments (0)