May 14, 2019

In this post I will describe how to add a full size image cover to your blog posts.

Nice thing about Gatsby that we can handle this very nicely with plugins while not taking care about manually serving different images for different screen sizes. Each device will receive it’s optimized version of the cover. Neat!

Assumptions

I will assume that you’ve already have your markdown set up. This means that you’ve got this plugins being installed and configured:

  • gatsby-source-filesystem
  • gatsby-transformer-remark

Instruction

#1. Editing Config

Make sure plugins are set up in your config.

// gatsby-config.js
module.exports = {
  /*
    ...
  */
  plugins: [
    /*
    ...
    */
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 620,
            },
          },
        ],
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    /*
      ...
    */
  ],
}

#2. Updating Markdown file

Put your image near your markdown file.

Update your markdown file (in my case it is post.md) to point cover field to an image.

---
title: 'How Failing With Pomodoro Technique Made Me 2x Better Programmer'
date: '2019-03-27'
cover: './cover.png'
---

Now let update your GraphQL queries.

#3. Updating GraphQL query

blog-post.js

const query = graphql`
  query BlogPostBySlug($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      id
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        title
        cover {
          publicURL
          childImageSharp {
            sizes(maxWidth: 2000) {
              ...GatsbyImageSharpSizes
            }
          }
        }
      }
    }
  }
`

Now you can edit your components code.

#4. Updating React Component

Make sure you have a gatsby-image installed. This is a component that will handle all the responsive magic.

yarn add gatsby-image

In order to display image full size I am passing cover data to my Layout component

<Layout
  location={props.location}
  title={siteTitle}
  cover={data.frontmatter.cover}
>
  {/* ... */}
</Layout>

And then I am displaying that data in my Layout component.

import Img from 'gatsby-image'

Component usage is quite simple. This is how I do it:

!!cover ? <Img sizes={cover.childImageSharp.sizes} /> : null

The end

Now you can be happy with your cool looking cover that is optimized to load fast for every device.


VERY good stuff is comming. You will like it. Subscribe!

Join 58 readers who gets it!


About the author
RG

Connecting concepts in a meaningful way. Looking for truth that will be surprising today and obvious tomorrow. © RG


Read more


© 2019, RG