About the Author:

Gatsby Tutorial Post Part 2: NetlifyCMS and Styling

April 29th, 2019

This is the 2nd part of a tutorial series on building fast and elegant sites with Gatsby, Material-ui, and NetlifyCMS (part 1 here). The previous part of the tutorial showed how to setup Gatsby and create pages manually as well as dynamically using gatsby-node.js. This part of the series will show the following:

  • Creating the Courses Page and Individual Courses
  • Adding Images to the Courses/Posts
  • Install Material-UI plugins and style all pages with Material-UI
  • Installing NetlifyCMS to allow non-technical users to make content changes
  • Adding More Fields Types to the Courses (that work out of the box with NetlifyCMS)

Demo Site (Here’s where we’re going to get to)

Github Repo (If you’d like to jump right into the code)

Creating the Courses Page and Individual Courses

Our demo site features both blogs (which we did previously) and courses (which we’ll do now). Similar to the blogs, this involves creating a parent /courses page, a course template, a courseitem component (for the list on /courses, and the markdown files for the courses. So let’s first create the main /courses page (that will list all of the courses) and pages for each course.

Here’s how I created each of the pages:

/pages/courses.js

import React from "react"
import { Link, StaticQuery, graphql } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"
import CourseItem from "../components/CourseItem"

class CoursePage extends React.Component {
 render() {
   const { data } = this.props

   const { edges: posts } = data.allMarkdownRemark

   return (
     <div>
       <Layout>
         <SEO title="Courses Page" />
         <h1>Courses Page</h1>

         <div
           style={{
             display: "flex",
             justifyContent: "space-evenly",
             flexWrap: "wrap",
           }}
         >
           {posts &&
             posts.map(({ node: post }) => (
               <CourseItem
                 key={post.id}
                 post={post.frontmatter}
                 style={{ marginRight: 10, width: "50%" }}
                 slug={post.fields.slug}
                 excerpt={post.excerpt}
               />
             ))}
         </div>
       </Layout>
     </div>
   )
 }
}

export default () => (
 <StaticQuery
   query={graphql`
     query CoursePageQuery {
       allMarkdownRemark(
         sort: { order: DESC, fields: [frontmatter___date] }
         filter: { frontmatter: { templateKey: { eq: "single-course" } } }
       ) {
         edges {
           node {
             excerpt(pruneLength: 100)
             id
             fields {
               slug
             }
             frontmatter {
               title
               templateKey
               date(formatString: "MMMM DD, YYYY")
             }
           }
         }
       }
     }
   `}
   render={data => <CoursePage data={data} />}
 />
)

/templates/single-course.js

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

const CoursePage = ({ data }) => {
 const { markdownRemark: post } = data

 return (
   <Layout>
     <Link to="/courses">
       <p>← Back to Courses</p>
     </Link>

     <h1>{post.frontmatter.title}</h1>
     <h4>{post.frontmatter.date}</h4>
     <p dangerouslySetInnerHTML={{ __html: post.html }} />
   </Layout>
 )
}

export default CoursePage

export const CoursePageQuery = graphql`
 query CoursePage($id: String!) {
   markdownRemark(id: { eq: $id }) {
     html
     frontmatter {
       title
     }
   }
 }
`

/components/courseitem.js

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

function CourseItem(props) {
 const { post, slug, excerpt } = props

 return (
   <div>
     <Link to={slug}>
       <h1>{post.title}</h1>
     </Link>
     <h3>{excerpt}</h3>
   </div>
 )
}

export default CourseItem

/courses/intermediate-react.md

---

templateKey: single-course

title: intermediate React

date: 2019-04-15T16:43:29.834Z

description: An intermediate React course

difficulty: Intermediate

---

what a course, what a course…….

/courses/cool-course.md etc

---

templateKey: single-course

title: Great course on JS

date: 2019-04-15T16:43:29.834Z

description: A great course

difficulty: Beginner

---

what a course, what a course...what a course, what a coursewhat a course, what a course...what a course, what a course

what a course, what a course...what a course, what a course

what a course, what a course...what a course, what a course

what a course, what a course...what a course, what a course

What’s going on here? Let’s review:

Gatsby-node.js creates the course pages using the appropriate template with this section of the code:

...

component: path.resolve(

`src/templates/${String(edge.node.frontmatter.templateKey)}.js`

),

…

In this case, it would be using single-course.js.

Within single-course.js there is a page query at the bottom. This queries for the right markdown file (using the id found in context) so that those specific pages will have the right title and html (from markdown) to display.

Within the courses.js file, we’re using a Static Query to query/search for the courses that have the templateKey of single-course and making a list of the courses (using the simple CourseItem.js component for help). This gives us a very basic (but functional) /courses page like this:

And an individual course page like this:

So these are pretty bland pages, unless you’re a hardcore minimalist. I’ll show you some Gatsby image plugins now that will add some color/life to these posts/courses.

Adding Images to the Courses/Posts

One of the top selling points of Gatsby is speed. Poorly sized or slow loading images are one of the easiest ways to make a website feel sluggish so this is an obvious area to optimize first. Two Gatsby plugins (gatsby-image and gatsby-transformer-sharp) are amazing tools for working with and optimizing Gatsby images. The latter leverages the Sharp image library, which is a very popular node module for resizing images. I’ll show you now to how add images to the course and post pages.

First, we need to install the plugins:

npm install --save gatsby-image gatsby-transformer-sharp gatsby-plugin-sharp

We’re also going to add a plugin that will allow us to access relative image paths in the project:

npm install gatsby-remark-relative-images --save

This will make for working with NetlifyCMS images easier later.

Then add them to the gatsby-config.js, within the big array of plugins like so:

 'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-relative-images',
          },
          {
            resolve: 'gatsby-remark-images',
            options: {
              // It's important to specify the maxWidth (in pixels) of
              // the content container as this plugin uses this as the
              // base for generating different widths of each image.
            
              maxWidth: 590,
            },
          },
          {
            resolve: 'gatsby-remark-copy-linked-files',
            options: {
              destinationDir: 'static',
            },
          },
        ],
      },
    },
{
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/static/img`,
        name: 'uploads',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/images`,
        name: 'images',
      },
    },

Now we can add the images to our posts. Create a folder called /static and a folder within that call img. That’s where the images will live. I downloaded some demo images for this fake courses and put them in the folder.

Now within the individual course markdown files, we need to add the images within the frontmatter (—) headings like so:

---

[more items]

image: /img/[imagename].jpeg

---

Now, we’ll edit the single-course.js page to be able to query for this image and render it on the page. Change the GraphQL query at the bottom of the page to include the image query, like so:

export const CoursePageQuery = graphql`
  query CoursePage($id: String!) {
    markdownRemark(id: { eq: $id }) {
      html
      frontmatter {
        title
        image {
          childImageSharp {
            fluid(maxWidth: 500, quality: 100) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

This is using the gatsby-plugin-sharp plugin to render a fluid image with a maxWidth of 500 pixels. Right here within the GraphQL query, we’re able to choose how we’d like to receive the image in our component/html. This plugin has extensive documentation that can be found here.

Now, within the the single-course.js, we’ll use Gatsby-image to render the image in the html. It’s a simple import:

import Img from "gatsby-image"

And then a simple enough component to render.

<Img fixed={post.frontmatter.image.childImageSharp.fluid} />

This is how you add the right plugins, the files, and the queries to be able to use plugins within Gatsby.

Installing NetlifyCMS

NetlifyCMS (like an CMS) allows for non-technical users to edit content on a site. This allows people in marketing or content roles the freedom to create and frees up developers from having to do these sorts of small tasks. As was mentioned before, NetlifyCMS is made by static hosting service Netlify, but they can each be used separately from each other. Gatsby can be easily configured to work with WordPress, Contently, and many other data sources. NetlifyCMS has great docs, a generous free tier, and easy-to-use authentication.

NetlifyCMS is easy to configure with Gatsby using, you probably guessed it, gatsby-plugin-netlify-cms. Install it using npm and add it to gatsby-config.js:

npm install gatsby-plugin-netlify-cms --save

// gatsby-node.js

},.......[other plugins]

`gatsby-plugin-netlify-cms`,

….[other plugins] {

NetlifyCMS needs a config.yml file, which tells it which fields can be changed within the CMS. Create a folder called ‘admin’ within the Static folder and put the following config.yml file in it:

backend:
  name: git-gateway
  branch: master

media_folder: static/img
public_folder: /images

collections:
  - name: "pages"
    label: "Pages"
    files:    
      - file: "src/pages/about.md"
        label: "About"
        name: "about"
        fields:
          - {
              label: "Template Key",
              name: "templateKey",
              widget: "hidden",
              default: "about-page",
            }
          - { label: "Title", name: "title", widget: "string" }
          - { label: "Body", name: "body", widget: "markdown" }
  - name: "blog"
    label: "Blog"
    folder: "src/pages/blogs"
    create: true
    slug: "{{year}}-{{month}}-{{day}}-{{slug}}"
    fields:
      - {
          label: "Template Key",
          name: "templateKey",
          widget: "hidden",
          default: "single-blog",
        }
      - { label: "Title", name: "title", widget: "string" }
      - { label: "Publish Date", name: "date", widget: "datetime" }
      - { label: "Description", name: "description", widget: "text" }
      - { label: "Body", name: "body", widget: "markdown" }

  - name: "courses"
    label: "Courses"
    folder: "src/pages/courses"
    create: true
    slug: "{{year}}-{{month}}-{{day}}-{{slug}}"
    fields:
      - {
          label: "Template Key",
          name: "templateKey",
          widget: "hidden",
          default: "single-course",
        }
      - { label: "Title", name: "title", widget: "string" }
      - { label: "Publish Date", name: "date", widget: "datetime" }
      - { label: "Description", name: "description", widget: "text" }
      - { label: "Body", name: "body", widget: "markdown" }
      - { label: Image, name: image, widget: image }

This creates 3 collections within the CMS: one for updating the about page, one for the courses, and one for the blogs. The ‘widgets’ are NetlifyCMS widgets and should be self-explanatory in a moment. With the above config.yml, this is what my admin interface looks like:

Within the Courses Collection, I see this:

Take a look, again, at the config.yml.

Notice how the fields with this file line up with what you’re seeing in the CMS image above? The template key is hidden so it doesn’t show. But right there are string widget (aka text field) for Title, Description, and Body. And there’s a datetime widget (a datepicker) for Publish Data. NetlifyCMS is really just an interface for making changes to our markdown files here. The config.yml serves as a way to tell Netlify which fields are available for editing. NetlifyCMS features a wide variety of default widgets and you can even make custom ones.

Source: https://www.netlifycms.org/docs/widgets/

Although this takes some setup work, this workflow is extremely powerful for using Github markdown files as a CMS.

The final thing needed here is making the images hosted in static/img available for NetlifyCMS to use.

Add this to the top of the file within Gatsby-node.js

const { fmImagesToRelative } = require('gatsby-remark-relative-images')

And add this method call within the onCreateNode block:

exports.onCreateNode = ({ node, actions, getNode }) => {

const { createNodeField } = actions

fmImagesToRelative(node)

This plugin was specifically built to make NetlifyCMS play nice with relative image paths. Failure to add this config right will send you to bug hell (e.g. “Field “image” must not have a selection since type “String” has no subfields.”)

.

Styling it all with Material-UI

We’ve built out our posts, blogs, and about page. Now we’ll see how to style out all of the pages using the most popular React UI framework, Material-ui. Material-ui has nearly 50,000 stars on Github and over 1,000 contributors. It is a React implementation of Google’s Material Design principles. Material-ui gives React developers a wide variety of components, styling, and utilities for making their sites aesthetically pleasing and easy to use. If you don’t want your site to look like a generic Googly app, Material-ui is supremely easy to customize to your liking.

There are many ways to add Material-ui to a Gatsby project. Material-ui has a Gatsby starter to use. Another developer made a dedicated Gatsby-starter with Material-ui. But I find the easiest way to add Material-ui to Gatsby is with gatsby-plugin-material-ui. The previous two work but they are much more complicated. Plugins are one of the awesome parts of Gatsby: Just install the plugin, add it to gatsby-config.js and you’re good to go. Here’s how to do just that:

npm install gatsby-plugin-material-ui @material-ui/styles

Edit gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-material-ui`,
      options: {
      },
    },
  ],
};

If you’ve worked with Material-ui before, you’ve probably played around with its theming capabilities. Material-ui themes allow you to establish a global theme that can be called from various child components. This makes it easier to create one coherent look and feel (vs. having pages/components with different styles, which can look sloppy). With the gatsby-plugin-material-ui plugin, this theme will go in that options object in the config above like so:

options: {        
        theme: {
          palette: {
              primary: {
                  main: '#BA3D3B', // new color here 
              } 
          },
      },

Now we can import material-ui components anywhere within the our Gatsby project. Here’s how I changed the single-course.js page:

imports...
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
...
import Avatar from '@material-ui/core/Avatar';

const styles = theme => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    padding: theme.spacing.unit * 2,
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
  title:{
    marginBottom:'.2em'
  },
  backButton: {
    textDecoration:'none'
  },
  bigAvatar: {
    '& img':{
      margin: 10,
      width: 60,
      height: 60,
    },
    width:100,
    height:100,
    border:'1px solid grey'
  
  },
});

const CoursePage = ({ data, classes }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
       <Link to='/courses' className={classes.backButton}>
      <p>← Back to Courses</p>

      </Link>
      
      <Grid container spacing={24}>
       
        <Grid item xs={9}>
          <h1 className={classes.title}>{post.frontmatter.title}</h1>
          <h4>{post.frontmatter.date}</h4>
          <p dangerouslySetInnerHTML={{ __html: post.html }}/>  
        </Grid>    
        <Grid item xs={3}>
        <Avatar src={post.frontmatter.image.childImageSharp.fluid.src} className={classes.bigAvatar} />
       
        </Grid>   
      </Grid>
  
    </Layout>
  )
}
export default withStyles(styles)(CoursePage);

[page query removed for brevity]

Here’s how I changed the single-blog template:

...
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
...
import Layout from '../components/layout'
import Img from "gatsby-image"
import { Link } from "gatsby"

const styles = theme => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    padding: theme.spacing.unit * 2,
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
  title:{
    marginBottom:'.2em'
  },
  backButton: {
    textDecoration:'none'
  }
});

const BlogPage = ({ data, classes }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
      <div className={classes.root}>
      <Link to='/blog' className={classes.backButton}>
      <p>← Back to Blog</p>

      </Link>
      
      <Grid container spacing={24}>
        <Grid item xs={3}>
          <Img fluid={post.frontmatter.image.childImageSharp.fluid} />
        </Grid>
        <Grid item xs={9}>
          <h1 className={classes.title}>{post.frontmatter.title}</h1>
          <h4>{post.frontmatter.date}</h4>
          <p dangerouslySetInnerHTML={{ __html: post.html }}/>  
        </Grid>       
      </Grid>
      </div>
    
    </Layout>
  )
}


export default withStyles(styles)(BlogPage);

[page query removed for brevity]
`

Here’s the about page:

...
import { withStyles } from '@material-ui/core/styles';

const styles = theme => ({
  heroText: {
    color:'white',
    textAlign: 'center',
    lineHeight:7,
    marginTop:-20
  },
  mainBlogCopy: {
    marginTop: theme.spacing.unit,
  },
  blogText:{
    color:theme.palette.primary.main
  }
});

const AboutPage = ({ data, classes }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
      <div style={{
        backgroundImage: `url(${post.frontmatter.image.childImageSharp.fluid.src})`,
        height:300
      }}>
      <h1 className={classes.heroText}>{post.frontmatter.title}</h1>
      </div>
      <div className={classes.mainBlogCopy}>
       <p className={classes.blogText} dangerouslySetInnerHTML={{ __html: post.html }}/> 
      </div>
      
    </Layout>
  )
}

AboutPage.propTypes = {
  data: PropTypes.object.isRequired,
}

export default withStyles(styles)(AboutPage);

[page query removed for brevity]

Here’s what I added to the home page to make it look a little more like appendTo:

….
import { Link, StaticQuery, graphql } from "gatsby"
import Grid from "@material-ui/core/Grid"
import BlogItem from "../components/BlogItem"
import { withStyles, withTheme } from "@material-ui/core/styles"
import Button from "@material-ui/core/Button"
import Typography from '@material-ui/core/Typography'
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';


const styles = theme => ({
  mainBlogArea: {
    paddingTop: '20px !important',

  },
  redBox:{
    padding:30,
    paddingTop:50,
    height:200,
    backgroundColor:'#AC4839',
    marginBottom:30
  },
  greyBox:{
    padding:30,
    paddingTop:50,
    height:200,
    backgroundColor:'#D9D8D8'
  },
  blackButton:{
    backgroundColor:'black',
    color:'white'

  },
  redButton:{
    backgroundColor:'#AC4839',
    color:'white'

  },
  TabsSection:{
    marginTop:30,
    backgroundColor:'white',
    border:'1px solid grey',
    height:300,
  },
  Tab:{
      width:10
  }

  
})

const IndexPage = props => {
  const { data, classes } = props
  // const { edges: posts } = data.allMarkdownRemark

  return (
    <Layout>
      <SEO title="appendTo Home" keywords={[`Courses`, `Training`, `react`]} />

      <Grid container spacing={24}  className={classes.mainBlogArea}>
        <Grid item xs={8}>
          <div >
            {data.map(item => (
              <BlogItem
                key={item.id}
                post={item.frontmatter}
                image={item.frontmatter.image.childImageSharp.fluid.src}
                slug={item.fields.slug}
                date={item.frontmatter.date}
              />
            ))}
          </div>
        </Grid>
        <Grid item xs={4}>
          <div className={classes.redBox}>
            <Typography variant="h5" style={{color:'white'}}>
              Custom Private Courses
            </Typography>
            <Button variant="contained" className={classes.blackButton}>
              Get Started
            </Button>
          </div>

          <div className={classes.greyBox}>
          <Typography variant="h5">
              Live Public Courses
            </Typography>
            <Button variant="contained" className={classes.redButton}>
              Sign Up Today
            </Button>
          </div>

          <div className={classes.TabsSection} >
          <AppBar position="static">
            <Tabs>
              <Tab label="Popular" className={classes.Tab} />
              <Tab label="Recent" className={classes.Tab} />
        
            </Tabs>
            </AppBar>


          </div>
        </Grid>
      </Grid>
    </Layout>
  )
}

const StyledUpIndexPage = withStyles(styles)(IndexPage)

export default () => (
  <StaticQuery
    query={graphql`
      query IndexPageQuery {
        allMarkdownRemark(
          sort: { order: DESC, fields: [frontmatter___date] }
          filter: { frontmatter: { templateKey: { eq: "single-blog" } } }
        ) {
          edges {
            node {
              excerpt(pruneLength: 40)
              id
              fields {
                slug
              }
              frontmatter {
                title
                templateKey
                date(formatString: "MMMM DD, YYYY")
                image {
                  childImageSharp {
                    fluid(maxWidth: 1400, quality: 100) {
                      ...GatsbyImageSharpFluid
                    }
                  }
                }
              }
            }
          }
        }
      }
    `}
    render={data => (
      <StyledUpIndexPage
        data={data.allMarkdownRemark.edges.map(item => item.node)}
      />
    )}
  />
)

And finally, here’s what I added to the NavBar to allow for navigating between the pages:

import { Link } from "gatsby"
import React from "react"
import { withStyles } from "@material-ui/core/styles"
import AppBar from "@material-ui/core/AppBar"
import Toolbar from "@material-ui/core/Toolbar"
import Button from "@material-ui/core/Button"

import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"


const styles = {
  root: {
    flexGrow: "1 !important",
  },
  appbar: {
    backgroundColor: "#AC493A",
  },
  grow:{
    flexGrow:1
  },
  link: {
    color: `white`,
    textDecoration: `none`,
  },
}

class Header extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { classes } = this.props

    return (
      <div className={classes.root}>
        <AppBar position="static" className={classes.appbar}>
          <Toolbar>
            <div className={classes.grow}>
              <Link to='/' >
              <StaticQuery
                query={graphql`
                  query {
                    file(relativePath: { eq: "appendto_logo.png" }) {
                      childImageSharp {
                        # Specify the image processing specifications right in the query.
                        # Makes it trivial to update as your page's design changes.
                        fixed(width: 150) {
                          ...GatsbyImageSharpFixed_noBase64
                        }
                      }
                    }
                  }
                `}
                render={data => <Img  critical={true} fadeIn fixed={data.file.childImageSharp.fixed} />}
              />
              </Link>
            </div>
            <div>
              <Link to="/about" className={classes.link}>
                <Button color="inherit">About</Button>
              </Link>

              <Link to="/blog" className={classes.link}>
                <Button color="inherit">Blog</Button>
              </Link>

              <Link to="/courses" className={classes.link}>
                <Button color="inherit">Courses</Button>
              </Link>
            </div>
          </Toolbar>
        </AppBar>
      </div>
    )
  }
}

export default withStyles(styles)(Header)

And here’s what we end up with: https://appendtostaticstyled.netlify.com/

We have here a site that we can continue to build upon and style with Material-ui. All users can make tweaks or changes using NetlifyCMS. And finally, this site is blazing fast and consists of static files that can be served for cloud storage service or CDN.

This starter project is a great way to start any project and I hope these two long posts helped you understand how it came together.

Recommended Reading

This tutorial showed you the essentials of Gatsby. That said, even with nearly 5500 words, it had to skip over a number of topics. Here’s some posts I recommend reading to get a better understanding of Gatsby:

About the Author:

Build Fast and Elegant Sites with Gatsby, NetlifyCMS and Material-UI

April 27th, 2019

This tutorial will show you how to use Gatsby, NetlifyCMS, Netlify, and Material-UI to build out a multi-page site that can be updated with an intuitive CMS. Before diving into the code, I’ll first tell you about the the tools we’ll be working with. Part 2 is here (if you need to skip ahead).

Gatsby

Gatsby is React-based framework that has recently gained a lot traction and use in production. AirBnb, Flamingo, and Impossible Foods are all companies using Gatsby to build production sites and apps. Gatsby sites get built with React, GraphQL, Gatsby plugins, and some sort of CMS. Gatsby outputs production assets as HTML/CSS/JS files that can be served from a cloud host like AWS S3 or a Google Cloud Storage Bucket.

Material-UI

Material-UI is a React UI framework that implements Google’s Material Design principles in React. It can be added to Gatsby projects in a variety of ways and we’ll see how to use it simply with a plugin.

Netlify/NetlifyCMS

One of the smaller hosting services that works really well with Gatsby is Netlify. Netlify (the company) authored an excellent CMS called NetlifyCMS that makes it really simple to produce/edit/manage content stored in Github. All in all, the combo of GraphQL, Netlify, and NetlifyCMS makes it really simple for developers (who already know React) to build fast websites with an intuitive CMS. NetlifyCMS can be setup so that non-technical users can easily make changes to the content and have Netlify push the changes live. Gone are the days of managing clunky WordPress sites or plugin catastrophes! Also gone are the days of slow loading heavy client side sites (looking at you Soundcloud and Yelp 👀).

Ok, whoah whoah — I’m mostly kidding. The WordPress ecosystem is actually pretty amazing and I use Soundcloud every dang day. What I mean to say is that Gatsby and the entire JAMstack paradigm represent a very exciting evolution in websites that developers will enjoy working on and people will enjoy using.

This tutorial will show you how to setup Gatsby with NetlifyCMS and build out a small demo site (see below). The goal of this tutorial is help give you a better conceptual framework for how Gatsby sites come together. Gatsby already has a very nicely done 8-part tutorial so this tutorial will seek to build upon that and make it even easier to learn Gatsby.

Tutorial Outline:

  • Part 1
    • What We’ll Build
    • About Gatsby (and why try it)
    • Setting up Gatsby
    • A high-level overview of what’s what in Gatsby
    • Understanding Gatsby’s Magic
    • Creating Basic Static Pages with Gatsby
    • Dynamically Creating Pages with gatsby-node.js
    • Creating the About Page
    • Creating the Blog Page and Blog Posts
  • Part 2
    • Setup NetlifyCMS to make editing the content more accessible
    • Create the Courses Page and Individual Courses
    • Add Images and more fields to the Courses and Blogs
    • Style it all with Material-UI

What We’ll Build

This tutorial will be focused on building a very basic clone of the appendTo site (that you’re on right now). This demo site consists of pages for About, Courses, Home, and the Blog. There will also be individual pages for each Course and Blog Post.

The site can be found here: https://appendtostaticstyled.netlify.com/courses

The content in this site lives in a Github repo and can be updated using NetlifyCMS. This gives developers or non-technical users a nice interface for making changes to the content.

About Gatsby (and why try it)

Gatsby is run by VC-backed Berkeley-based Gatsby Inc., which has almost 30 employees (at this time of writing). Many of their founders and employees have ‘making the web fast’ as their Linkedin tagline so it’s fair to say that speed is one Gatsby’s primary selling points. Definitely take a second to try out of some of the sites listed on the Gatsby showcase page. The speed at which an attractive, image-heavy ecommerce site like ShopFlamingo.com loads should inspire you to pick up Gatsby. There’s a pure simple joy in clicking on something and having it load near instantaneously.

The fact that Gatsby is being run as a business and used by large companies should give developers confidence that Gatsby will be around for a while and support will be above average. I find it confidence-inspiring that there are more than 5,000 closed issues on Github.

Furthermore, I received extremely fast help for anything I struggled with while making this post (via Discord, Github, and StackOverflow).

It’s also worth taking a look at some of the blog posts that Gatsby employees have written about their baby. A very interesting one is Making website building fun by founder Kyle Mathews. The whole essay is worth reading and gives you a sense of their founding principles. Mathews describes using the component React-headroom vs. having to implement the same functionality, from scratch, in HTML/CSS/JS (with many more lines). One of the key lines in that essay is this:

What makes technology fun?

This is a complex philosophical question and I’m writing this on a Saturday afternoon so I’ll cheat a bit and just cut the gordian knot by saying “simplicity is fun” and conversely, “complexity is not fun”.

Every one loves new projects. Why? Because they’re simple! We can dive in and experiment and reliably get something done. The more complex the project, the more things seem to break, the more time gets wasted on various yak shaves, and critically, the gap between thinking up an idea and being able to try it grows larger and larger.

Why am I mentioning this bit or the founder at all? Because Gatsby was designed to make building websites more fun. This likely explains the development of their plugin ecosystem and some of the magic and opinions Gatsby has. There’s some upfront difficulty and complexity in learning to play with Gatsby. But once you get it, you’ll probably find it really fun to use.

If you’re still considering other static site options, compare Gatsby with React-static to see how a more manual and less opinionated React-based static site library can look.

And with this background out of the way, let’s start building!

Setting up Gatsby

Gatsby offers a nifty CLI for working with Gatsby projects. As you probably guessed, here’s the terminal command to get it:

npm install -g gatsby-cli

Like many CLIs, typing gatsby –help in the Terminal shows you some of the new commands you can use:

Let’s use gatsby new now to create a new Gatsby project:

gatsby new appendToGatsby

After that build completes, run gatsby develop in the terminal and open http://localhost:8000/ in your browser. Pull the project folder into your text editor of choice.

Take a look at the files and folders generated by the Gatsby CLI. I don’t know about you, but I often feel a bit overwhelmed when I see a whole bunch of new files and folders that a generator has made for me. I sometimes claw through the files frantically trying to figure out what’s what and how it all wires together. To make this easier for you, I’m going to diagram this out.

You should be seeing a folder for components, pages, images and several .js files that live in the src root. Here’s a quick rundown on what they do:

Here’s what you should be seeing:

The hardest thing about Gatsby (for me) was all the little nuances and small details that make up its functionality. For example, with this starter project, I found myself looking for the React-router files and a base app.js. Don’t do this! Gatsby projects work differently than normal Create-React-App projects. Let’s create a new page and learn more.

Take what’s in page-2.js and create a file called coolnewpage.js (in that same /pages folder)

Mine looks something like this:

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

import Layout from "../components/layout"
import SEO from "../components/seo"

const CoolNewPage = () => (
 <Layout>
   <SEO title="Cool New Page" />
   <h1>Cool New Page</h1>
   <p>Gatsby is Magical but worth learning</p>
   <Link to="/">Go back to the homepage (index.js file)</Link>
 </Layout>
)

export default CoolNewPage

Then re-run gatsby develop in your terminal. Now when I go to http://localhost:8001/coolnewpage, I see this:

Of course this is nothing too special. But consider that you didn’t have to setup the routing or link the components together. Gatsby just detected that a new file was in the pages folder and created the page for it. Try to let some of your React habits go when learning Gatsby (suspend disbelief, if you will). This will make sense with a bit of practice. Let’s now try building something a bit more dynamic.

Building a dynamic About page

Building static pages (by literally placing them in the /pages folder) works fine and would be a good option for really simple ‘brochureware’ sites or a portfolio. But since you’ll likely want to build sites with multiple pages and templates, it makes sense to learn how to use data and templates to build pages dynamically.

We’re next going to build out the About page for this appendTo clone site. Building pages dynamically is quite challenging at first but it’s fairly easy to pick up. Here are the steps:

  1. Create a markdown file (with frontmatter headings) that will hold the page content
  2. Use the Gatsby API methods createPages and onCreateNode to create the page(s) in gatsby-node.js
  3. Create the page template with the appropriate GraphQL query to populate the page with data
  4. Install the appropriate plugins and add them to gatsby-config

It’s hard to understand how these files and APIs connect at first. I’ll walk you through it as slowly and simply as possible.

Step 1: Create the markdown files

Create a markdown file called about.md (that will go in the /pages folder) with the text/info that will go on the about page. Frontmatter (the information between the two triple dashes —) is where you can store fields like the title and the templateKey (which I’ll explain in a bit). Mine looks something like this:

about.md

templateKey: about-page

title: About Page (created with gatsby-node.js)

(This text is obnoxiously red on purpose)

appendTo is your leading source of technical news, tips, and tutorials.

[the rest of the post]

…..

Step 2: Create the pages using the Gatsby API methods in gatsby-node

We need to now create the pages using Gatsby’s createPages and onCreateNode API methods.

const path = require(`path`)
const { createFilePath } = require('gatsby-source-filesystem')

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

 return graphql(`
   {
     allMarkdownRemark(limit: 1000) {
       edges {
         node {
           id
           fields {
             slug
           }
           frontmatter {
             templateKey
           }
         }
       }
     }
   }
 `).then(result => {
   if (result.errors) {
     result.errors.forEach(e => console.error(e.toString()))
     return Promise.reject(result.errors)
   }


   const posts = result.data.allMarkdownRemark.edges

   posts.forEach(edge => {
     const id = edge.node.id
     createPage({
       path: edge.node.fields.slug,
       tags: edge.node.frontmatter.tags,
       component: path.resolve(
         `src/templates/${String(edge.node.frontmatter.templateKey)}.js`
       ),
       // additional data can be passed via context
       context: {
         id
       },
     })
   })
 })
}

 exports.onCreateNode = ({ node, actions, getNode }) => {
   const { createNodeField } = actions
  
    if (node.internal.type === `MarkdownRemark`) {
     const value = createFilePath({ node, getNode, basePath: `pages` })
     createNodeField({
       name: `slug`,
       node,
       value,
     })
   }
 }

Gatsby’s docs say “We do our best to make Gatsby APIs simple to implement.” I think they do an ok job here but it’s still a lot to grok. It doesn’t make sense for me to completely rehash part 7 of their tutorial where they explain this all in great depth. For this tutorial’s sake, I’ll give you the quick version of what’s going on in the code above.

The onCreateNode part below this is for creating the slugs field so that the page urls work properly. Similar to how that coolnewpage.js created a page at /coolnewpage above, this is doing so manually.

In essence, gatsby-node.js is in charge of querying the markdown files and then creating pages (and slugs) using the markdown data and the page templates. Now we need to create the appropriate page template so that this about page can be created.

Step 3: Create the page templates and their GraphQL queries

Next you need to create a /templates folder and a template for this page. My /templates/about.js page looks like this:

import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import Layout from '../components/layout'

const AboutPage = ({ data }) => {
 const { markdownRemark: post } = data

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

AboutPage.propTypes = {
 data: PropTypes.object.isRequired,
}

export default AboutPage;

export const aboutPageQuery = graphql`
 query AboutPage($id: String!) {
   markdownRemark(id: { eq: $id }) {
     html
     frontmatter {
       title
     }
   }
 }
`

This looks similar to a normal React component, except for the graphql query at the bottom. This query is using the id passed to the context (on gatsby-node.js) to find the appropriate page (where that id matches). It then retrieves the html and the title from that page (aka, the markdown file). Remember this little bit at the bottom of the previous file?

That same ‘id’ is being used in the query right here to get the right page data.

Step 4: Install Plugins

The final thing we need to do is add the right plugins for us to be able to work with the file system and query markdown files.

Terminal

npm install --save gatsby-source-filesystem

npm install --save gatsby-transformer-remark

Within gatsby-config.js, you need to add these plugins into that [plugins array]:

   {
     resolve: `gatsby-source-filesystem`,
     options: {
       name: `src`,
       path: `${__dirname}/src/`,
     },
   },
  ….
   },
...
...
  `gatsby-transformer-remark`,

Then restart the server with gatsby develop and check out the new about page:

The first time doing this can feel a little challenging. There’s a lot of different files being used and it’s pretty easy for things to break. To prevent myself from getting lost in the cognitive overload of Markdown, React, config settings, GraphQL, React context, promises, and nested you-name-its, I came up with mental shorthand for what these files do:

Markdown files: The data that will go into the pages. Easy.

Templates in the /templates folder: React components with GraphQL queries at the bottom used to build the Gatsby static pages.

Gatsby-node.js: Finds my markdown files and creates pages/slugs for them using the right page template.

Gatsby-config.js: Array of plugins and settings I have to touch when installing plugins.

I hope these shorthands help you as you build your mental model of how Gatsby works.

If you need help understanding how to work with GraphQL in Gatsby, Gatsby comes with a built in GraphQL explorer/helper tool called GraphiQL. Gatsby’s tutorial also has a good write up on how to use it.

Creating the Blog Page and Blog Posts

Now that you’ve made an About page, creating other pages is fairly simple. Since appendTo (and the clone we’re building) is primarily a blog page, we’ll now create some blog posts. This involves creating three new files:

  1. /pages/blog.js (the parent /blog page with a list of the blog posts)
  2. /pages/blogs/blog1.md (an example of the markdown files for the blogs)
  3. /components/BlogItem.js (a small component to show the blog excerpt and title on the /blog page)
  4. /templates/single-blog.js (template for just one blog post)

Here’s how I created the blogs:

Step 1: Create blog.js

import React from "react"
import { StaticQuery, graphql } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"
import BlogItem from "../components/BlogItem"

class BlogPage extends React.Component {
 render() {
   const { data } = this.props
   const { edges: posts } = data.allMarkdownRemark

   return (
     <Layout>
       <SEO title="Blog" />
       <h1>Blog Page</h1>
       <div>
         {posts &&
           posts.map(({ node: post }) => (
             <BlogItem
               key={post.id}
               post={post.frontmatter}
               slug={post.fields.slug}
               excerpt={post.excerpt}
             />
           ))}
       </div>
     </Layout>
   )
 }
}

export default () => (
 <StaticQuery
   query={graphql`
     query BlogPageQuery {
       allMarkdownRemark(
         sort: { order: DESC, fields: [frontmatter___date] }
         filter: { frontmatter: { templateKey: { eq: "single-blog" } } }
       ) {
         edges {
           node {
             excerpt(pruneLength: 40)
             id
             fields {
               slug
             }
             frontmatter {
               title
               templateKey
               date(formatString: "MMMM DD, YYYY")
             }
           }
         }
       }
     }
   `}
   render={data => <BlogPage data={data} />}
 />
)

This page looks similar to our about page. It is a React component with a GraphQL query at the bottom. This Static Query is a Gatsby component that can be used anywhere to query for data. In this case, it is querying for markdown files that have a templateKey of ‘single-blog’ in the frontmatter header. Let’s make these markdown files now.

Step 2: Create markdown blog files

Here’s an example blog I created and filled with hipster ispum. Notice the templateKey line at the top there. That’s what the query above (in my /blog.js file is looking for).

---

templateKey: single-blog

title: blog3

date: 2019-04-10T16:43:29.834Z

description: so stoked on blog3

---

astropub, small batch godard kickstarter sustainable shoreditch raw denim affogato twee. Disrupt normcore lumbersexual, craft beer aesthetic iPhone chambray irony glossier vinyl skateboard tbh fanny pack. Banh mi sartorial hot chicken semiotics roof party PBR&B whatever brunch, kombucha XOXO tumblr helvetica skateboard. Church-key chillwav

Now we need to make the BlogItem.js component that /blog.js can render this data into.

Step 3: Create BlogItem.js

BlogItem.js

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

function BlogItem(props) {
 const { post, slug, excerpt } = props

 return (
   <div>
     <div>
       <Link to={slug}>
         <h1>{post.title}</h1>
       </Link>
       <h3>{post.date}</h3>
       <p>{excerpt}</p>
     </div>
   </div>
 )
}

export default BlogItem

This is a fairly standard React component that uses the Gatsby Link component for linking to other pages.

Restart the development server and you should see this in your browser:

Step 4: Create the single-blog.js template

import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import Layout from '../components/layout'

const BlogPage = ({ data }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
      <p>{post.frontmatter.title}</p>
       <p> {post.html}  </p>
      />
    </Layout>
  )
}

BlogPage.propTypes = {
  data: PropTypes.object.isRequired,
}

export default BlogPage

export const BlogPageQuery = graphql`
  query BlogPage($id: String!) {
    markdownRemark(id: { eq: $id }) {
      html
      frontmatter {
        title
      }
    }
  }

Clicking on one of the blogs will lead you to this:

To review what’s happening here, the main /blog page is querying for blog markdown files (e.g. blog1.md), then passing this data to itself and rendering a list of blogs using the BlogItem components.

This post covered most of the basics of setting up Gatsby and creating pages manually and automatically using gatsby-node.js. The following post will explore the following:

  • Creating the Courses Page and Individual Courses
  • Installing NetlifyCMS
  • Styling it all with Material-UI