Learn Gatsby · 6/12

Transforming Data: From Markdown to Web Pages

6 min read

Transforming Data: From Markdown to Web Pages 📄➡️💻

Welcome back! So far, we've wrangled our data sources, but there's a small hiccup. Gatsby, out of the box, is like a brilliant chef who has all the raw ingredients but doesn't know the recipe. It sees your Markdown files, for instance, but just sees them as plain text. It doesn't inherently understand that ## Hello World is supposed to be a big, beautiful heading on a webpage.

That's where the magic of transformer plugins comes in. They are the recipe books that teach Gatsby how to cook your raw data into something delicious and usable for your website.


1. Understanding Transformer Plugins in Gatsby 🕵️‍♂️

Definition: A transformer plugin in Gatsby takes raw data from a source plugin (like a Markdown file from gatsby-source-filesystem) and transforms it into a more useful format. For example, it can convert Markdown syntax into HTML.

The Problem: You've used gatsby-source-filesystem to tell Gatsby, "Hey, look at these files in my src/posts directory!". Gatsby nods and says, "Okay, I see a file named my-first-post.md." But that's it. It doesn't know how to read the content of the Markdown file and understand its structure (headings, lists, bold text, etc.).

The Solution: Transformer plugins are specialized tools that process the content of sourced nodes. Think of it like a language translator. Your Markdown file speaks "Markdown-ish," and your website needs to understand "HTML-ish." The transformer plugin is the translator that makes this communication possible.

Gatsby's ecosystem has a transformer for almost everything:

  • gatsby-transformer-remark for standard Markdown.
  • gatsby-transformer-json for JSON files.
  • gatsby-transformer-sharp for optimizing images.

The cool part? You can chain these plugins. One plugin sources the data, and another transforms it. This creates a powerful and flexible data pipeline.


2. Parsing Standard Markdown with gatsby-transformer-remark 📝

This is the workhorse for most Gatsby blogs. It takes your plain Markdown files and turns them into HTML that can be rendered on a page.

The Problem: You've written a beautiful blog post in a .md file, complete with frontmatter (the metadata at the top, like title and date). How do you get Gatsby to understand this and create a blog post page from it?

Getting Started with gatsby-transformer-remark

First, you need to install it, along with its peer gatsby-source-filesystem if you haven't already.

Step 1: Installation
Open your terminal and run:

bash
npm install gatsby-transformer-remark gatsby-source-filesystem

Step 2: Configuration
Now, you need to tell Gatsby to use these plugins. Open your gatsby-config.js file and configure them.

javascript
// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/posts/`, // Path to your markdown files
      },
    },
    `gatsby-transformer-remark`,
  ],
}

What’s happening here?

  • gatsby-source-filesystem: This plugin tells Gatsby to look for files in the src/posts/ directory and create "File" nodes from them.
  • gatsby-transformer-remark: This plugin then looks at all the nodes created by other plugins. When it finds a "File" node with a mediaType of text/markdown, it swoops in and says, "I know what to do with this!" It then creates a new MarkdownRemark node that contains the parsed HTML and frontmatter.

✨ Fun Fact: Under the hood, gatsby-transformer-remark uses a library called remark to do the heavy lifting of parsing Markdown. This is a great example of the open-source community building on top of each other's work!


3. Querying Transformed Markdown Nodes via GraphQL 🧐

Now that your Markdown is transformed, it's time to pull that data into your pages. This is where GraphQL comes in.

The Problem: Your Markdown content is now neatly organized into MarkdownRemark nodes. But how do you access this data from your React components to actually display it?

The Solution: You can use GraphQL to query for this data. Gatsby automatically adds the transformed data to its GraphQL schema, making it available to query.

Let's say you have a Markdown file at src/posts/hello-world.md:

markdown
---
title: "Hello, World!"
date: "2024-01-01"
---

This is my **first** blog post!

You can now run a GraphQL query in a page or component to get this data. A common use case is to create a page for each blog post.

Example GraphQL Query:

You can test this query in the GraphQL Playground, which is usually running at http://localhost:8000/___graphql.

graphql
query {
  allMarkdownRemark {
    nodes {
      frontmatter {
        title
        date
      }
      html
      excerpt
    }
  }
}

What this query does:

  • allMarkdownRemark: This tells GraphQL you want to get all nodes of the type MarkdownRemark.
  • nodes: This is the array containing each individual post's data.
  • frontmatter: This object contains all the metadata you defined at the top of your Markdown file.
  • html: This is the transformed Markdown content, now in HTML format.
  • excerpt: This is a short, auto-generated summary of your post.

With this query, you can now map over the nodes in your React component to display a list of all your blog posts. It's like having a superpower to ask for exactly the data you need, and nothing more.


4. Next-Level Content: Using MDX to Embed React Components 🚀

Standard Markdown is fantastic for static content. But what if you want to add a custom chart, a newsletter signup form, or an interactive quiz right in the middle of your blog post? This is where MDX shines.

Definition: MDX is an extension of Markdown that allows you to write JSX (the syntax used by React) directly in your Markdown files.

The Problem: Markdown is limited. You can't easily add interactive React components. You'd have to write the component separately and then figure out a way to inject it into your page, which can be clunky.

The Solution: MDX lets you import and use React components seamlessly within your content.

Getting Started with MDX

Step 1: Installation
You'll need to install the gatsby-plugin-mdx and its dependencies.

bash
npm install gatsby-plugin-mdx @mdx-js/react

Step 2: Configuration
Update your gatsby-config.js to use gatsby-plugin-mdx.

javascript
// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/posts/`,
      },
    },
    `gatsby-plugin-mdx`,
  ],
}

Step 3: Create an MDX File
Now, you can create .mdx files instead of .md.

Let's say you have a React component for a styled message box: src/components/MessageBox.js.

javascript
// src/components/MessageBox.js
import React from 'react';

const MessageBox = ({ children }) => (
  <div style={{ padding: '1rem', border: '1px solid rebeccapurple' }}>
    {children}
  </div>
);

export default MessageBox;

You can now use this directly in an .mdx file:

mdx
---
title: "My First MDX Post"
date: "2024-02-01"
---

import MessageBox from '../components/MessageBox';

## This is an MDX Post!

Check out this cool message box:

<MessageBox>
  This is a React component inside my Markdown! How cool is that?
</MessageBox>

MDX opens up a world of possibilities for creating rich, interactive content. It's the perfect blend of simple content creation with the power of React.


Further Reading 📚

Challenge

You are tasked with setting up a Gatsby project to render a blog from local Markdown files. The Markdown files are all located in a directory at the path src/content/posts.

  1. In the provided gatsby-config.js skeleton, configure the gatsby-source-filesystem plugin to source files from the src/content/posts directory.
  2. Next, add the gatsby-transformer-remark plugin to the configuration to process the sourced Markdown files.
  3. Finally, in the space provided, write a complete GraphQL query that retrieves data for a blog listing page. The query must fetch all Markdown nodes, sort them by their date frontmatter field in descending order, and for each post, retrieve its generated html and its title from the frontmatter.

Expected result

The gatsby-config.js file must be correctly populated.

  • The plugins array must contain an object for the gatsby-source-filesystem plugin.
  • This object's options property must specify the path as 'src/content/posts'.
  • The plugins array must also contain the string 'gatsby-transformer-remark'.

A valid GraphQL query must be provided below the configuration.

  • The query must use the allMarkdownRemark field.
  • It must include a sort argument to order the results by the date field within frontmatter in DESC (descending) order.
  • The fields requested for each post must include html, and within frontmatter, the title field.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.