How to Use Blurbs for a Gatsby Blog

February 07, 2018

When you use Gatsby’s starter for creating a blog, it displays an excerpt of the post’s body on the list page. In my case though, I wanted the ability to display a custom blurb instead.

A blurb is defined as a short description of a book, movie or article. In some cases, it’s better to use this customizable bit of data rather than the first 250 characters of your post. However, I wanted this to be optional. Fortunately, Gatsby and a little bit of JavaScript makes this easy to achieve.

First, add a blurb to the front matter of your post. In the case of this article, the front matter looks like this:

---
title: How to Use Blurbs for a Gatsby Blog
date: "2018-02-07"
path: "/how-to-use-blurbs-for-a-gatsby-blog/"
blurb: Learn how to use blurbs instead of excerpts when listing posts.
---

Then, edit the GraphQL query in your index.js to include blurb:

// index.js
export const pageQuery = graphql`
  query IndexQuery {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      edges {
        node {
          excerpt
          frontmatter {
            path
            date(formatString: "MMMM DD, YYYY")
          }
          frontmatter {
            title
            blurb
          }
        }
      }
    }
  }
`

(Your query may look different from the above. The important part is to add blurb beneath frontmatter.)

The last step is to actually display the blurb. Still in index.js, find where the excerpt is injected into a p tag. It’ll look something like this:

<p dangerouslySetInnerHTML={{ __html: node.excerpt }} />

Change it to:

<p
    dangerouslySetInnerHTML={{
        __html: node.frontmatter.blurb || node.excerpt
    }}
/>

Essentially we’re saying “if a blurb exists, inject it into the p tag, otherwise inject the excerpt.”

Your posts will render the same as they would before, but now you have the option of using a custom blurb instead of an automatically generated excerpt.


Hi, I'm Steven Mercatante.
I build awesome things for the web using Python, JavaScript and Elixir.
Contact me if you'd like to work together.