How to Build a React and Gatsby-Powered Blog in About 10 Minutes

Gatsby is a powerful static site generator that lets you build blazing fast websites and apps with React. It‘s an excellent choice for creating blogs, portfolios, documentation sites, and more.

In this tutorial, I‘ll walk you through building a complete Gatsby-powered blog from scratch. You‘ll learn how to set up a new Gatsby site, create pages and components, query data with GraphQL, generate pages from Markdown, and deploy your shiny new blog.

The best part? If you have the prerequisites in place, you can go from zero to a live Gatsby blog in about 10 minutes! Let‘s dive in.

Prerequisites

Before getting started, make sure you have the following installed:

You should also have basic familiarity with HTML, CSS, JavaScript, and React. Prior Gatsby experience is helpful but not required.

Setting up a New Gatsby Site

Gatsby provides a command line interface (CLI) for generating new sites and running common tasks. Install the Gatsby CLI globally with npm:

npm install -g gatsby-cli

Next, navigate to the directory where you want to create your site and use the gatsby new command to set up a new site:

gatsby new my-gatsby-blog 

This command generates a new directory called my-gatsby-blog with the initial project structure and configuration.

Navigate into the directory and start the local development server:

cd my-gatsby-blog
gatsby develop

You can now view your new site at http://localhost:8000. You‘ll see a basic homepage with some default content and styling.

Configuring Gatsby Plugins

Gatsby has a rich plugin ecosystem that lets you easily add new features to your site. Plugins can source data, transform data, implement search, handle responsive images, and much more.

Your site already has a few useful plugins set up in the gatsby-config.js file:

module.exports = {
  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-image`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    // ...
  ],
}

Let‘s add two more plugins to support loading Markdown content and generating pages:

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

Configure the plugins in gatsby-config.js:

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

The gatsby-source-filesystem plugin will load Markdown files from the content directory. The gatsby-transformer-remark plugin will parse Markdown content into HTML.

Creating Pages and Components

Now you‘re ready to start building out the pages and components for your blog. Gatsby follows a standard directory structure:

  • Pages go in src/pages
  • Components go in src/components
  • Images and other assets go in src/images

Let‘s create a simple header component in src/components/header.js:

import React from ‘react‘
import { Link } from ‘gatsby‘

const Header = () => (
  <header>

    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
      </ul>
    </nav>
  </header>
)

export default Header

Next, create a src/components/layout.js component that will serve as the common layout for pages:

import React from ‘react‘
import Header from ‘./header‘

const Layout = ({ children }) => (
  <>
    <Header />
    <main>{children}</main>
    <footer>
      My Great Gatsby Blog © {new Date().getFullYear()}
    </footer>
  </>
)

export default Layout

With these components in place, update src/pages/index.js to use the Layout component:

import React from ‘react‘
import Layout from ‘../components/layout‘

const HomePage = () => (
  <Layout>

    <p>This is the home page content.</p>
  </Layout>  
)

export default HomePage

Finally, create an src/pages/about.js page:

import React from ‘react‘  
import Layout from ‘../components/layout‘

const AboutPage = () => (
  <Layout>

    <p>This is the about page content.</p>
  </Layout>
)

export default AboutPage

Restart the development server and you should see your updated homepage with the new layout applied. Clicking the "About" link in the header will take you to the newly created About page.

Generating Pages from Markdown

Now let‘s generate some actual blog post pages from Markdown files. First, create a couple of Markdown files in the content/posts directory:

content/posts/hello-world.md:

---
title: Hello World
date: 2023-03-25
---

This is my first blog post! I‘m excited to start sharing my thoughts and experiences.

content/posts/second-post.md:

---
title: My Second Post  
date: 2023-03-26
---

I‘m getting the hang of this blogging thing. Stay tuned for more insights!

The section surrounded by --- at the top is called frontmatter. This is where you can specify metadata about the post, like the title and date. The Markdown content follows below.

To generate blog post pages, you‘ll use the Gatsby Node API in gatsby-node.js:

const path = require(‘path‘)

exports.createPages = async ({ actions, graphql }) => {
  const { createPage } = actions

  const result = await graphql(`
    query {
      allMarkdownRemark {
        nodes {
          frontmatter {
            title
          }
          fields {
            slug
          }
        }
      }
    }
  `)

  const postTemplate = path.resolve(‘src/templates/post.js‘)

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

This code queries all the Markdown files, then generates a new page for each one using a post.js template component. The slug field is generated automatically based on the file name.

Create the src/templates/post.js template component:

import React from ‘react‘
import { graphql, Link } from ‘gatsby‘
import Layout from ‘../components/layout‘

const PostTemplate = ({ data }) => {
  const { markdownRemark } = data
  const { frontmatter, html } = markdownRemark

  return (
    <Layout>
      <article>

        <time>{frontmatter.date}</time>
        <div dangerouslySetInnerHTML={{ __html: html }} />
      </article>
      <Link to="/">Back to Home</Link>
    </Layout>
  )  
}

export const query = graphql`
  query($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        title
      }
    }
  }
`

export default PostTemplate

This component queries an individual Markdown post by its slug, then renders the title, date, and HTML content within the Layout component.

The last step is to update src/pages/index.js to list the blog posts with links:

import React from ‘react‘
import { graphql, Link } from ‘gatsby‘
import Layout from ‘../components/layout‘

const HomePage = ({ data }) => {
  const posts = data.allMarkdownRemark.nodes

  return (
    <Layout>

      <h2>Recent Posts</h2>
      <ul>
        {posts.map(post => (
          <li key={post.fields.slug}>
            <Link to={post.fields.slug}>{post.frontmatter.title}</Link>
          </li>
        ))}
      </ul>
    </Layout>
  )
}

export const query = graphql`
  query {
    allMarkdownRemark(sort: { frontmatter: { date: DESC } }) {
      nodes {
        frontmatter {
          title
        }
        fields {
          slug
        }
      }
    }
  }
`

export default HomePage

Restart the development server and you should now see your blog posts listed on the homepage. Clicking a post title will take you to the individual post page.

Deploying Your Gatsby Blog

To build your site for deployment, stop the development server and run:

gatsby build

This generates production-ready files in the public directory. You can deploy these files to any static hosting service, such as Netlify, Vercel, or GitHub Pages.

For example, to deploy with Netlify:

  1. Push your code to a Git repository
  2. Log in to Netlify and click "New site from Git"
  3. Select your repository and branch
  4. Specify gatsby build as the build command and public as the publish directory
  5. Click "Deploy site"

Next Steps

Congratulations, you now have a fully functioning Gatsby blog! Some next steps and additional features to consider:

  • Customize the site design and styles to make it your own
  • Add support for blog post tags/categories
  • Implement client-side search with Algolia
  • Integrate Disqus for post comments
  • Set up an RSS feed or email newsletter
  • Enable offline functionality with a service worker

The beauty of Gatsby is that you can gradually level up your site as you go. Start with the basics, then layer on more advanced functionality as needed.

I hope this tutorial has given you a solid foundation for building your own Gatsby blog. For more information and inspiration, check out the Gatsby docs and showcase. Happy blogging!

Similar Posts

Leave a Reply

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