Creating a new blog post in gatsby
Here's a step-by-step guide on how to create a new blog post in Gatsby:
Prerequisites
- You have a Gatsby project set up on your local machine.
- You have installed the
gatsby
command-line interface (CLI) globally on your machine. - You have a basic understanding of Gatsby and its file structure.
Step 1: Create a new blog post file
In your Gatsby project, navigate to the src/pages
directory and create a new file with a name that follows the convention blog-post-<slug>.mdx
. For example, blog-post-my-new-blog-post.mdx
.
Step 2: Write your blog post content
In the new file, write your blog post content in Markdown format. You can use Markdown syntax to format your text, add headings, links, images, and more.
Here's an example of what your blog post file might look like:
---
title: My New Blog Post
date: 2023-02-20T14:30:00.000Z
slug: my-new-blog-post
---
This is my new blog post. It's a great day to write about something new!
Step 3: Add metadata
In the front matter of your blog post file, add metadata such as the title, date, and slug. The metadata will be used to generate the blog post's URL and metadata.
Step 4: Create a new blog post component
In your Gatsby project, create a new file in the src/components
directory called BlogPost.js
. This file will contain the React component that will render your blog post.
Here's an example of what your BlogPost.js
file might look like:
import React from 'react';
import { MDXRenderer } from 'gatsby-plugin-mdx';
const BlogPost = ({ data }) => {
const { frontmatter, html } = data.mdx;
return (
<div>
<h1>{frontmatter.title}</h1>
<MDXRenderer>{html}</MDXRenderer>
</div>
);
};
export const query = graphql`
query BlogPostQuery($slug: String!) {
mdx(fields: { slug: { eq: $slug } }) {
frontmatter {
title
}
html
}
}
`;
export default BlogPost;
Step 5: Add the blog post to your Gatsby site
In your gatsby-config.js
file, add a new entry to the routes
array that points to your new blog post component.
Here's an example of what your gatsby-config.js
file might look like:
module.exports = {
//... other configurations...
routes: [
{
path: '/blog/:slug',
component: './components/BlogPost',
},
],
};
Step 6: Run Gatsby to build and start your site
Run the following command in your terminal to build and start your Gatsby site:
gatsby develop
Your blog post should now be available at http://localhost:8000/blog/my-new-blog-post
.