Outline

Let's start learning how to add images to Markdown and MDX files. The first way is to include an image in our Markdown frontmatter.

Pick one of the Markdown files in /content/events and add a new frontmatter property called banner that points to an image inside of the same folder (you may need to copy or move an image into it):

---
date: "2019-11-16"
title: "Woodworking Basics: The Table Saw"
category: "Series"
banner: "./sawing.jpg"
---

Continuing our series on Woodworking Basics, this week we'll learn all about the table saw.

Next, we need to modify the event layout (src/pages/event-layout.js). We need to modify the query and add it to the page. In the query, we just need to add banner to our frontmatter object. This will actually be an ImageSharp node, so we can pull back that same childImageSharp item we've seen before:

// src/pages/event-layout.js
export const pageQuery = graphql`
  query EventPageQuery($id: String) {
    mdx(id: { eq: $id }) {
      body
      frontmatter {
        date(formatString: "MM/DD/YYYY")
        title
        category
        banner {
          childImageSharp {
            fluid {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
      id
    }
  }
`

Let's import Gatsby Image and styled-components next:

import Image from "gatsby-image"
import styled from "styled-components"

Next, let's create a BannerImage component:

const BannerImage = styled(Image)`
  border-radius: 10px;
  max-width: 400px;
  margin-top: 20px;
`

Finally, we can add that image to the page, but we don't want to forget to check for null. Here's how the final code looks:

export default ({ data: { mdx } }) => {
  return (
    <Layout>
      {mdx.frontmatter.banner && (
        <BannerImage
          fluid={mdx.frontmatter.banner.childImageSharp.fluid}
          alt="Banner Image"
        />
      )}
      <h3>Name: {mdx.frontmatter.title}</h3>
      <h3>Date: {mdx.frontmatter.date}</h3>
      <h3>Category: {mdx.frontmatter.category}</h3>
      <MDXRenderer>{mdx.body}</MDXRenderer>
    </Layout>
  )
}

If you run gatsby develop and visit that page, you should see your image with the fancy blurred placeholder.

Let's take a quick detour and extract that BannerImage component into its own file so we can reuse it throughout the application.

 

I finished! On to the next chapter