Gatsby.js Practice Exercise: Building a Blog
In this exercise, you’ll use Gatsby to build a simple blog.
- Create a new Gatsby project: Run the following command in your terminal to create a new Gatsby project:
javascriptCopy codegatsby new gatsby-blog
- Start the development server: Navigate into the “gatsby-blog” directory and start the development server by running the following command:
bashCopy codecd gatsby-blog
gatsby develop
- Install the gatsby-source-filesystem plugin: To be able to retrieve your blog post data from the file system, you’ll need to install the “gatsby-source-filesystem” plugin. You can do this by running the following command in your terminal:
Copy codenpm install gatsby-source-filesystem
- Configure the gatsby-source-filesystem plugin: Open the “gatsby-config.js” file and add the following code to configure the “gatsby-source-filesystem” plugin:
javascriptCopy codemodule.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `posts`,
path: `${__dirname}/src/posts`,
},
},
],
}
- Create a new post: In the “src/posts” directory, create a new file named “first-post.md” and add the following content to it:
yamlCopy code---
title: "My First Post"
date: "2023-02-12"
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod orci vel ante tincidunt, non egestas elit dictum. Integer volutpat nisl nisl, eget fringilla enim blandit vel.
- Create a template for blog posts: In the “src/templates” directory, create a new file named “post.js” and add the following code to it:
javascriptCopy codeimport React from "react"
import { graphql } from "gatsby"
const PostTemplate = ({ data }) => {
const post = data.markdownRemark
return (
<div>
<h1>{post.frontmatter.title}</h1>
<p>{post.frontmatter.date}</p>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</div>
)
}
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
date
}
}
}
`
export default PostTemplate
- Create a page for the blog post: In the “src/pages” directory, create a new file named “first-post.js” and add the following code to it:
pythonCopy codeimport React from "react"
import { graphql } from "gatsby"
import PostTemplate from "../templates/post