zocada

Deep dive into Gatsby – Building a static blog using Gatsby, React and GraphQL

Gatsby.js is one of the most exciting technologies happened in this decade. Building lightning fast websites have never been easier before. Gatsby combines the flexibility of React and benefits of GraphQL to build static websites. Not to confuse with what Gatsby does, the description provided in the website gives a clear idea on what Gatsby is.

Gatsby.js is one of the most exciting technologies happened in this decade. Building lightning fast websites have never been easier before. Gatsby combines the flexibility of React and benefits of GraphQL to build static websites. Not to confuse with what Gatsby does, the description provided in the website gives a clear idea on what Gatsby is.

Gatsby.js is a static PWA (Progressive Web App) generator. You get code and data splitting out-of-the-box. Gatsby loads only the critical HTML, CSS, data, and JavaScript so your site loads as fast as possible. Once loaded, Gatsby prefetches resources for other pages so clicking around the site feels incredibly fast.

Official Gatsby website.

Getting Started

Gatsby provides an amazing CLI to kickstart any Gatsby project easily. Most of this tutorial is concentrated on Linux/Mac machines. You are good to go if you are using Windows with the latest version of Node.js and NPM installed. If you don’t have both installed checkout our articles on how to install Node.js and npm on Linux/mac Systems and Windows

Step 1. Installing Gatsby-CLI

Gatsby CLI is a simple tool that helps us to use Gatsby starter templates. Here we’ll be using a simple starter template with bare basic boilerplate. Fire up a terminal and execute the following command to install Gatsby-CLI using npm

npm install -g gatsby-cli

This will quickly install Gatsby-CLI on your system. Next we’ll jump into using a starter template to build up our blog.

Note: All the code used in this article and the sample project created is available in our GitHub repo. Head over there to have a sneak peek on how things should look if you get lost anywhere between the instructions below.

Step 2. Creating a new project with a starter

Once you are ready with Gatsby CLI, we can head on to creating your first Gatsby project. Navigate your terminal into your desired directory and execute the following command.

gatsby new my-blog

This will clone the Gatsby-Starter-Default and execute an npm install to install all the dependencies and plugins.

Step 3. Starting gatsby Dev Server

cd into the project folder and open up your favorite editor (Obviously, VSCODE ❤). Fire up a terminal and run gatsby develop inside the project directory to start the dev server.

Once the server is up, you can visit localhost:8000 in your browser to see a delightful Gatsby landing page.

Awesome! you have successfully finished the basic steps! now, let’s get into coding!

Step 3. Understanding the project structure.

Under the hood, Gatsby projects are react applications. Well, it’s a complete react application, the only part Gatsby comes in is to build the site by executing all the graphql queries, optimizing images, importing necessary data from sources and breaking down the site into static contents using technologies like webpack. If you have a background in developing with React, the current project structure might seem familiar.

my-blog/
│
├── node_modules/
│   └── [You don't wanna get in here]
│
├── public/
│   ├── [Your site's static contents]
│   └── [Automatically generated by gatsby]
│
├── src/
|   ├── components/
│   │   ├── [These are the building blocks of your website]
│   │   └── [All your react components]
│   │
│   ├── images/
│   │
│   └── pages/
│       ├── 404.js [Your site's 404 page]
│       ├── index.js [the front/first page of your site]
│       └── page-2.js [yet another page]
│
├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── gatsby-ssr.js
├── package.json
├── package-lock.json
└── LICENSE

Let’s take a close look at what these files and directories are..

node_modules/ : This directory contains all of the modules of code that your project depends on (npm packages) are automatically installed.

public/ : Contains automatically generated static build of your site. This is automatically done by Gatsby on issue of the command gatsby build or gatsby develop

src/ : This directory will contain all of the code related to what you will see on the front-end of your site (what you see in the browser) such as your site header or a page template. src is a convention for “source code”.

src/components/ : This sub-directory will contain all the components you require as the building blocks of react application.

src/pages/ Gatsby treats this directory differently, any Javascript files added as a react component in this directory will be treated as a page of your website. You can simply navigate to each of these pages from your browser without the file extension. eg. localhost:8000/404 or localhost:8000/page-2, where as the index.js will be treated as your default landing page.

gatsby-browser.js : This file is where Gatsby expects to find any usage of the Gatsby browser APIs (if any). These allow customization/extension of default Gatsby settings affecting the browser.

gatsby-node.js : This file is where Gatsby expects to find any usage of the Gatsby Node APIs (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process.

gatsby-ssr.js : This file is where Gatsby expects to find any usage of the Gatsby server-side rendering APIs (if any). These allow customization of default Gatsby settings affecting server-side rendering.

gatsby-config.js : This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you’d like to include, etc. (Check out the config docs for more detail).




Step 4. Installing necessary Plugins

Gatsby is all about JAM Stack, if you are new to the concept:

JAMstack: noun \’jam-stak’\
Modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup.

Here, we’ll be using markdown to write our blogs and GraphQL to query our markdown files (just like an API) and display the data using React. So, we need a few of the Gatsby plugins to get started with writing blogs in markdown and querying them using GraphQL. Execute the following command inside your project directory to install the necessary plugins.

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

Applying your plugins

We need to specify to Gatsby on which plugins we are using so that Gatsby can use them to integrate to our project’s workflow. Add the following lines into your gatsby-config.js file to enable the plugins. Before doing this we need to create a directory to store all our posts, which will be written in markdown. So, create a new subdirectory inside the src/ directory as posts. Your directory structure should look somewhat like this now.

.
.
.
├── src/
|   ├── components/
│   ├── pages/
│   ├── posts/  <-- The directory you need to create
│   └── images/
│   
.
.

Now apply the plugins in gatsby-config.js so as your file should look like this.

We are creating our blog posts and querying them as markdown files. Gatsby uses the Remark library to achieve this. Since we already installed the plugin, we can write down our blog posts in markdown files and put them inside the posts directory. A sample post will look similar to this.

---
slug: /my-first-blog-post
date: 2018-10-27
author: Jhone Doe
title: My first blog post on gatsby
---

The contents of your blog in either markdown or html.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

You might be wondering what the --- dashes are? The part enclosed with dashes are called as the frontmatter of your file. It's commonly used in Jekyll as a handy way to store additional data in the markdown. The data inside the markdown is written in YAML format. You can learn more about the YAML syntax in here. Note that, the slug in your frontmatter is the relative url of your blog in your website. That is, where your blog post will be visible.

Create a couple of blog posts in the src/posts/ subdirectory so that we can start working on creating the home page of our website which lists all the blog posts.

.
.
.
├── src/
|   ├── components/
│   ├── pages/
│   ├── posts/ 
│   │   ├── my_first_blog.md
│   │   ├── my_second_blog.md
│   │   └── my_third_blog.md
│   └── images/
│   
.
.

Step 5. Using GraphQL to fetch data and display on home page

Gatsby provides out of the box support for using GaraphQL and comes with a built-in GraphiQL IDE. If you have ran gatsby develop on your terminal, You'll might have seen gatsby printing out an additional URL to to the Graphiql as localhost:8000/___graphql. Let's create a graphQL query to fetch the title of the blog posts to display them in the home page. Hop into the GraphQL editor at localhost:8000/___graphql from your browser and execute the following query to get the JSON data of all the posts.

query postsQuery {
    allMarkdownRemark (
        sort: { fields: [frontmatter___date], order: DESC } 
    ) {
        edges {
          node {
            frontmatter {
              slug
              title
            }
          }
        }
    }
}

We won't be going in much depth into GraphQL in this post, but for the record: The edges means, we are letting graphQL know that we are looking for an array, and the node mentioning how each element should look like. The contents inside the node is pretty much staright forward on mentioning what we are querying from the markdown files.

You can change the src/pages/index.js to look like this to use graphQL to fetch data and pass them into a React component.

Once you have made the above changes by removing un-necassry elements from your src/pages/index.js file and added the GraphQL query. Restart the dev server. You'll be able to see your website on the browser now listing all the blogposts you have created.

All the links will render a 404 error page since we haven't created any page to display the content of our blog post yet.





Step 6. Creating template to display blog posts

In this step, we'll create a simple template to render the contents of our blog post into a template and view them on the slug url specified. So, let's start by creating a new sub-directory inside src/ as src/templates/. Create a new file named as blog_template.js and add the following lines of code. Which includes a simple react component and a GraphQL query to fetch data from a specific url supplied by gatsby.

Step 7. Using Gatsby's Node APIs to generate Pages

We need to interact with the Gatsby's Node APIs to tell Gatsby to use all the markdown files and generate the pages using the template we created above. Open the gatsby-node.js file and add the following code to complete building of your simple blog using Gatsby.

In here, we are using the Gatsby's createPages() node API to tell Gatsby to execute a query to find all markdown files and using the template, create pages at the slug provided in the frontmatter of the file.

Restart the Gatsby dev server and goto localhost:8000 to view your website and click on any of the blog links to view your live blog posts. Yaaaay!

We'll look more into How we can add cover images and style our static blog in an upcoming post. Till then, Cheers!





Also published on Medium.

haxzie

Community Lead with a demonstrated history of working in a non-profit organization. Skilled in Python, Public Speaking, Graphic Design, Writing, and Android Development. Strong community and social services professional with a Bachelor's degree focused in Computer Science from Sahyadri College of Engineering and Management.