Categories
Gatsby.js

Gatsby.js — Rendering Markdown Data

Spread the love

Gatsby is a static web site framework that’s based on React.

We can use it to create static websites from external data sources and more.

In this article, we’ll look at how to create a site with Gatsby.

Markdown Data

We can get data from Markdown files and use them as a data source.

To do this, we install the gatsby-transformer-remark and gatsby-source-fulesystem plugins to get the Markdown files from a given folder.

We install gatsby-transformer-remark by running:

npm install gatsby-transformer-remark

And we install gatsby-source-filesystem by running:

npm install gatsby-source-filesystem

Then we write:

gatsby-config.js

/**
 * Configure your Gatsby site with this file.
 *
 * See: https://www.gatsbyjs.com/docs/gatsby-config/
 */

module.exports = {
  /* Your site config here */
  plugins: [
    `gatsby-transformer-remark`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `content`,
        path: `${__dirname}/src/content`,
      },
    },
  ]
}

src/content/hello-world.md

---
title: Hello World
date: 2020-07-10
path: /hello-world
---

hello world

We get the Markdown files from the src/content folder.

The top part is the front matter, which we’ll use to create our page.

And when we run gatsby develop and go to http://localhost:8000/__graphql, we can query the Markdown files by writing:

{
  allMarkdownRemark {
    edges {
      node {
        frontmatter {
          path
        }
      }
    }
  }
}

Then we get:

{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "frontmatter": {
              "path": "/hello-world"
            }
          }
        }
      ]
    }
  },
  "extensions": {}
}

from the response.

Now we need to create the page from the Markdown file.

To do this, we write:

gatsby-node.js

const path = require(`path`)
exports.createPages = async ({ actions, graphql }) => {
  const { createPage } = actions
  const result = await graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            frontmatter {
              path
            }
          }
        }
      }
    }
  `)
  if (result.errors) {
    console.error(result.errors)
  }
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.frontmatter.path,
      component: path.resolve(`src/templates/post.js`),
    })
  })
}

src/templates/post.js

import React from "react"
import { graphql } from "gatsby"
export default function Template({ data }) {
  const { markdownRemark } = data
  const { frontmatter, html } = markdownRemark
  return (
    <div className="blog-post">
      <h1>{frontmatter.title}</h1>
      <h2>{frontmatter.date}</h2>
      <div
        className="blog-post-content"
        dangerouslySetInnerHTML={{ __html: html }}
      />
    </div>
  )
}
export const pageQuery = graphql`
  query($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        path
        title
      }
    }
  }
`

In gatsby-node.js , we make the same query we made in GraphiQL.

And then we get the response and call createPage to create the page with the path to the file as defined in the Markdown’s front matter.

And the component has the template to render the front matter and content.

In post.js , we get the data from the data prop.

We get the title and date properties from the frontMatter object to get the front matter data and display them.

Then the content is in the markdownRemark.html property.

Now when we go to http://localhost:8000/hello-world, we see:

Hello World
July 10, 2020
hello world

displayed.

Conclusion

We can render data from Markdown in our Gatsby static site.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *