Using Gatsby-Plugin-Image With Contentful

Diederik Mathijs
2 min readJul 26, 2021

--

Why the new Gatsby-Plugin-Image is so amazing and why you should be using it.

If you’re looking into finding your ideal CMS for your next blog site, look no further. It works perfectly with Gatsby.js (which doesn’t need an introduction anymore) and is called Contentful.

If you’ve worked with React, you’ll know that you can use imports to import images from a specific folder and then use it in your HTML-markup

import diamondImage from '../images/diamond.png'const DiamondImage = () => {
return (
<img src={diamondImage} alt="a diamond!" />
)
}

Problem is that this causes your images to be loaded directly, which might end up influencing your lighthouse audit score as your pages will take longer to load.

The new and improved version of gatsby-image called gatsby-image-plugin allows us to easily load our images dynamically. This is exactly what we want to do because we’ll have to load our images from Contentful without blocking our page loading.

Let me show you how you can do it quite easily.

Using Gatsby-plugin-image

Ensure that you have gatsby-image-plugin installed in your project (most likely it’s part of the starter you’ve started from).

If not you can simply run npm i gatsby-image-plugin

Then add the plugin to your gatsby-config.js and complete your installation.

Next, we import the necessary library on our page to allow the rendering of our dynamic images:

import { GatsbyImage, getImage } from "gatsby-plugin-image"

Contentful is great because it directly supports gatsby-plugin-image . Take a look at our GraphQL query:

export const query = graphql`
{
allContentfulBlog(filter: {node_locale: {eq: "en-US"}}) {
edges {
node {
blogIntroImage {
gatsbyImageData(width:200)
}
}
}
}
}`

As you can see we perform a query for our current locale (en-US) and fetch the blogIntroImage of all our blogs. We then force the image to a width of 200px, note that we could pass other options like the ones described on the gatsby website.

After having executed our query, we can now use our resulting blogIntroImage on our blog:

{data.allContentfulBlog.edges.map(({ node: blogItem }) => {
const image = getImage(blogItem.blogIntroImage)
return (
<div>
<GatsbyImage image={image} alt="blog image" />
</div>)
})}

That’s it! Your images should load on the page without any issues! Using GraphQL and gatsby-plugin-image will have a great impact on your loading time and you’ll see your performance score rocket!

--

--

Diederik Mathijs

Senior .NET/React developer writing about technical topics surrounding Javascript.