loader

WHAT'S NEW

Part 2: Building a Dynamic Blog with Gatsby & Markdown: A Guide for Developers

October 17, 2023

Hey up and coming Gatsby developer! Lets start where we stopped off in part 1. This is part two of he article: “Create A Dynamic Blog With Gatsby & Markdown”-
Continue on your journey of producing a blog with Gatsby & Markdown, by following the last few steps below.

Step 1: Create a Blog Listing Page

  1. In your Gatsby project directory, navigate to the src/pages folder.
  2. Create a new file called blog.js. This will be your blog listing page.

Step 2: Query Your Blog Posts

  1. In blog.js, import GraphQL from Gatsby by adding this line at the top of the file:
import { graphql } from "gatsby";

2. Define a GraphQL query to retrieve your blog posts. Add this query to the blog.js file:

export const query = graphql`
  query {
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      edges {
        node {
          id
          frontmatter {
            title
            date(formatString: "MMMM DD, YYYY")
          }
          fields {
            slug
          }
        }
      }
    }
  }
`;

3. This query fetches all Markdown blog posts, sorts them by date in descending order, and retrieves their title, date, and slug.

Step 3: Create a Component to Display Blog Posts

  1. Create a new file in your src directory called BlogList.js.
  2. In BlogList.js, create a component to display your blog posts. You can map over the data obtained from the GraphQL query and render each blog post. Here’s a simplified example:
import React from "react";

const BlogList = ({ data }) => {
  const posts = data.allMarkdownRemark.edges;

  return (
    <div>
      <h1>Blog Posts</h1>
      <ul>
        {posts.map(({ node }) => (
          <li key={node.id}>
            <h2>{node.frontmatter.title}</h2>
            <p>{node.frontmatter.date}</p>
            <a href={node.fields.slug}>Read more</a>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default BlogList;

Step 4: Render the Blog List

  1. In blog.js, import React and the BlogList component you just created:
import React from "react";
import BlogList from "../components/BlogList";

2. Pass the GraphQL query data to the BlogList component as a prop:

const BlogPage = ({ data }) => {
  return (
    <div>
      <BlogList data={data} />
    </div>
  );
};

export default BlogPage;

Now, when you visit /blog, you’ll see a dynamic list of your blog posts.

Creating Dynamic Blog Pages

First Step: Create a Blog Template

  1. In your Gatsby project directory, navigate to the src/templates folder.
  2. Create a new file called blogTemplate.js. This will serve as the template for individual blog posts.

Second Step: Query Individual Blog Posts

  1. In blogTemplate.js, define a GraphQL query to retrieve an individual blog post based on the slug. Add this query to the file:
export const query = graphql`
  query($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
      }
      html
    }
  }
`;
  1. This query fetches the title, date, and HTML content of the blog post with the specified slug.

Third step: Create a Component to Display Individual Blog Posts

  1. Create a new file in your src directory called BlogPost.js.
  2. In BlogPost.js, create a component to display individual blog posts. You can use the data obtained from the GraphQL query to render the post. Here’s a simplified example:
import React from "react";

const BlogPost = ({ data }) => {
  const post = data.markdownRemark;

  return (
    <div>
      <h1>{post.frontmatter.title}</h1>
      <p>{post.frontmatter.date}</p>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </div>
  );
};

export default BlogPost;

Last step: Generate Blog Pages

  1. In your gatsby-node.js file, create a function to generate blog pages for each Markdown file. You can use the createPages API provided by Gatsby.
const path = require("path");

exports.createPages = async ({ actions, graphql }) => {
  const { createPage } = actions;
  const blogTemplate = path.resolve("./src/templates/blogTemplate.js");

  const result = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `);

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: blogTemplate,
      context: {
        slug: node.fields.slug,
      },
    });
  });
};

This code queries all the Markdown files and creates individual blog pages using the blogTemplate.js template.

With these steps in place, you can now navigate to individual blog posts by clicking on the “Read more” link on the blog listing page, and each post will have its unique URL and content.

Congratulations! You now have a dynamic blog list and individual blog pages set up on your Gatsby site, all managed through Git source control. This approach allows you to easily add, edit, and showcase your blog posts while maintaining full control over your content and source code. Happy blogging!

Not a Gatsby Developer and needing some more help?


Should you feel you need some more guidance or a more beginner friendly platform, we can guide you in the right direction, give us a shout! There are many different ways of producing a blog, with or without the ability to code. You don’t need to be a Gatsby developer to create a blog.

Facebook
WhatsApp
Reddit
Twitter
LinkedIn
CODE, WEB & DIGITAL CHATTER

MORE THOUGHTS

Digital Agency Cape Town

© 2023 | Trinity Managed Solutions (PTY) LTD
Privacy Policy

Top
×