May 14, 2019
by Rohov Dmytro
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!
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-filesystemgatsby-transformer-remarkMake 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`,
/*
...
*/
],
}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.
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.
Make sure you have a gatsby-image installed. This is a component that will handle all the responsive magic.
yarn add gatsby-imageIn 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} /> : nullNow you can be happy with your cool looking cover that is optimized to load fast for every device.