© Alex Libby 2021
A. LibbyGatsby E-Commercehttps://doi.org/10.1007/978-1-4842-6692-2_7

7. Adding a Blog

Alex Libby1  
(1)
RUGBY, UK
 

So far, we’ve constructed the beginnings of our online store – we still have a way to go before we can release it to the paying public, but that will come with time! However, there is one key element that is missing for us.

Although many e-commerce sites focus on selling products, many will include some form of social contact – a great example is a blog. It adds a personal touch to the whole shopping experience and potentially gives shoppers ideas on what to buy that they may otherwise have not considered.

For this next project, we will look at adding such a blog, focusing on how we can fit it into the shop so that it becomes an integral part of the experience and link to products that customers can buy directly from the site.

Setting the Scene

Okay, so where shall we start?

That’s a good question. Let me answer that by setting the scene: we’re going to create a simple blog using tools already at our disposal, plus a couple of new ones.

This blog certainly won’t break any awards in terms of styling or functionality but will focus on providing a solid ground on which we can build and develop a more fully fleshed-out affair. For this tool, we will, of course, use Gatsby, but this time around, use Markdown as our data source.

At this point, I can hear you ask: why use yet another data source when we already use GraphQL? It’s a great point: we could easily use GraphQL, which would be a perfectly acceptable option. However, I would say this: why not use another data source? The creators of Gatsby designed it to consume data from multiple sources, so this should be a walk in the park for the tool. It also gives you a flavor of how we can mix in new functionality to an existing site.

Okay, enough chitchat. Let’s crack on with coding! To give you a flavor for how our site will start to look, take a look at Figure 7-1, which shows a screenshot of the completed blog, with some styling applied.
../images/499924_1_En_7_Chapter/499924_1_En_7_Fig1_HTML.jpg
Figure 7-1

A screenshot of the finished article

We have a few steps to work through before we see that for real – the first one is to download and install a couple of plugins that are required to transform Markdown files into content suitable for hosting in the blog.

Installing the Required Plugins

As with any project, we need to start somewhere, so there is no better place than to get and install any plugins we need to construct the blog. Fortunately, there is only one additional plugin we need to install; we will use a second, but this we set up as part of setting up the original site theme (gatsby-source-filesystem).

The plugin in question is gatsby-transformer-remark; we use it to transform Markdown pages into something we can display as valid pages in our blog. It only takes a handful of steps to get it installed and configured, so let’s dive in and take a look at the steps required in more detail.

ADDING THE PLUGINS FOR OUR BLOG
The first step to getting our blog set up is to get the plugins installed – to do this, work through these steps:
  1. 1.

    First, we need to create two new folders to store content – go ahead and create the assets and blog folders at the root of the src folder in our project area.

     
  2. 2.

    We have two plugins to install, so crack open a Node.js terminal session, and change the working folder to our project area.

     
  3. 3.

    Next, enter this command at the prompt, and press Enter:

     
npm install gatsby-transformer-remark gatsby-remark-images
  1. 4.

    Once we finish installing these two plugins, you can minimize or close the Node.js terminal session – we don’t need it for the remainder of this exercise.

     
  2. 5.

    The next task is to tell Gatsby about the new plugin, plus tweak the configuration for an existing plugin. For this, crack open the gatsby-config.js file, and look for this line of code:

     
`gatsby-plugin-react-helmet`,
  1. 6.
    Immediately below it, add in this block:
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            path: `${__dirname}/src/assets`,
          },
        },
     
  2. 7.
    We have another, similar, block to add in – add this immediately below the code from step 5:
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            path: `${__dirname}/src/blog`,
          },
        },
     
  3. 8.

    With that in place, there is one more block to add in – this configures the newly added gatsby-transformer-remark plugin. Look for this line of code:

     
`gatsby-plugin-sharp`,
  1. 9.
    Add in the following code, immediately below the code from step 7:
        {
          resolve: `gatsby-transformer-remark`,
          options: {
            plugins: [
              {
                resolve: `gatsby-remark-images`,
                options: {
                  maxWidth: 800,
                },
              },
            ],
          },
        },
     
  2. 10.

    Go ahead and save the file and then close it – we’re now ready to add in the source files required to create our blog.

     

Completing this exercise is a significant step forward – we now have the requisite plugins in place and configured, so we can go ahead with constructing our blog! We’ve made a few changes in this demo that are key to the success of the blog working, so it’s worth us pausing for a moment to review these changes in more detail.

Understanding the Changes

Although we’ve worked through a few steps in this last exercise, the reality is that much of what we’ve done is standard fare when it comes to installing NPM-based plugins.

We started by installing two plugins, gatsby-transformer-remark and gatsby-remark-images . The former we will use to convert Markdown files into a format suitable for our blog, and the latter processes images referenced in those files so that Gatsby can insert them during the build process.

We then ran through several steps to add in resolve references for each plugin, plus two for the (already installed).

This latter plugin needs to take files from several locations (one for posts, another for images); the configuration entries tell it where to look for source files.

Okay, let’s crack on: we have the plugins installed, so let’s turn our attention to writing the first of our code files – the main blog page.

Creating the Main Blog Page

Okay, so what’s next? Well, now that we have the plugins installed and configured, we can crack on with adding in the blog code!

The first step is to update the existing blog.js page we already have on the site; we’ll use this to display a summary list of all of the posts created in the blog. In a nutshell, we will replace the existing blog.js file in its entirety; let’s dive in and make a start on updating this file.

CREATING THE MAIN BLOG PAGE
To create the main blog page , follow these steps:
  1. 1.

    First, crack open a copy of the blog.js file in your text editor – the file is in the srccomponents folder.

     
  2. 2.

    Highlight and remove all of the code within – the result will look very different from what it is now!

     
  3. 3.
    Go ahead and add in the following code, which we will do block by block, starting with the necessary component or function imports:
    import React from "react"
    import Sidebar from "./sidebar"
    import { Link } from "gatsby"
    import { graphql } from 'gatsby'
     
  4. 4.
    We then add in the main default function for this component – leave a line blank after the import statements, and then add in this:
    export default function Index({ data }) {
      return (
    <...INSERT CODE HERE...>
      );
    }
     
  5. 5.

    Go ahead and replace <...INSERT CODE HERE...> with this constant, to reference all of the Markdown files we will be compiling into the blog:

     
  const { edges: posts } = data.allMarkdownRemark;
  1. 6.
    This next block takes care of rendering what customers see on-screen; the first part adds in a title and sidebar to the blog summary page:
          <h1>Blog</h1>
          <div style={{ display: 'flex', flexDirection: 'column', width: '300px' }}>
            <Sidebar
              title="About Author"
              description="Phasellus a ex scelerisque, cursus mi eu, vehicula risus. Ut ac pharetra ipsum. Ut tortor sem, laoreet non cursus vel, imperdiet at nisi."
            />
          </div>
     
  2. 7.
    Immediately below this, we need to add in this <div> which iterates through all of the posts to provide the summary list on the page:
          <div className="blog-posts">
            {posts
              .filter(post => post.node.frontmatter.title.length > 0)
              .map(({ node: post }) => {
                return (
                  <div className="blog-post-preview" key={post.id}>
                    <h2>
                      <Link to={post.frontmatter.path}>{post.frontmatter.title}</Link>
                    </h2>
                    <span className="published">{post.frontmatter.date} by {post.frontmatter.author}</span>
                    <p>{post.excerpt}</p>
                  </div>
                );
              })}
          </div>
     
  3. 8.
    There is one more block to add, which is the GraphQL statement that requests the data from our Markdown files – leave a line blank at the end of the Index function, and then add this code:
    export const pageQuery = graphql`
      query IndexQuery {
        allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
          edges {
            node {
              excerpt(pruneLength: 250)
              id
              frontmatter {
                title
                date(formatString: "MMMM DD, YYYY")
                path
                author
              }
            }
          }
        }
      }
    `;
     
  4. 9.
    We need to add in another component, which is the Sidebar; for this, crack open a new file, and add in the following code:
    import React from "react";
    const Sidebar = (props) => (
      <div style={{
        border: '2px solid #e6e6e6',
        width: '200px',
        padding: '0.5rem',
        marginBottom: '25px',
          marginLeft: '50px',
          fontSize: '14px'
        }}>
          <strong style={{ display: 'flex' }}>
            {props.title}.
          </strong>
            {props.description}
        </div>
      );
      export default Sidebar
     
  5. 10.

    Go ahead and save this as sidebar.js in the srccomponents folder.

     
  6. 11.

    Go ahead and extract copies of the srcassets and srclog folders from the code download that accompanies this book; save them to the root of the src folder in our project area.

     
  7. 12.

    You can close any files still open – the changes are now complete for the main blog page.

     

We are one step closer to a working blog! Okay, if we run up gatsby develop to view the site, you may well find it doesn’t show any blog posts.

This lack of posts is to be expected, as we need to make changes to the gatsby-node.js file for it to trigger the compilation process for Markdown files. That will come a little later in this chapter, but for now, let’s pause for a moment to review the code we’ve added in as part of this last exercise.

Breaking Apart the Code

This last exercise was a lengthy affair, but necessary – the changes that we’ve made to the original blog.js page are so substantial it’s become a new page in its own right!

We started with the usual requisite imports before setting up the placeholder for the Index function that we will export from this component. We then began to add in the code for the blog page – the first addition was to display a Sidebar component to show details about the author of this mini-blog.

We then moved on to adding a container for the blog posts (in the form of blog-posts) before iterating through each Markdown file and mapping the content of them into the relevant fields on-screen. This content took the form of displaying the post.frontmatter.path (where the file was stored), the post.frontmatter.date (the date of writing the post), the post.frontmatter.author value (for the author of the post), and post.excerpt, before finishing with a GraphQL query used to return the values from the Markdown files.

We then finished the demo by adding in the code for a new Sidebar component, which we referenced in the blog.js page; this we use to render the content about the author on-screen.

Creating the Blog Template

With the main summary page set up and ready for us to use, the next step is to create a template that we can use to display the content for each blog post.

The blog template is a new component; we will use it when we update the gatsby-node.js file to generate the blog post pages automatically a little later in this chapter. Before we do that, let’s first take a look at the steps required to set up the template in more detail.

CREATING THE BLOG TEMPLATE
To get the template set up ready for use, follow these steps:
  1. 1.
    Crack open your text editor, and then add the following code to a new file, saving it as blog-template.js in the src emplates folder. We’ll go through it block by block, starting with the requisite declarations:
    import React from "react";
    import Helmet from "react-helmet";
    import { graphql } from 'gatsby'
    export default function Template({  data }) {
      const post = data.markdownRemark;
     
  2. 2.
    This next block is the main return statement – this is where each blog post will be rendered on-screen to the customer:
      return (
          <div className="blog-post-container">
           <Helmet title={`HaveCakeEatCake - ${post.frontmatter.title}`} />
            <div className="blog-post">
            <h3>{post.frontmatter.title}</h3>
            <p>published {post.frontmatter.date} by {post.frontmatter.author}</p>
            <div className="blog-post-content" dangerouslySetInnerHTML={{ __html: post.html }} /></div>
          </div>
        );
    }
     
  3. 3.
    The final part of this component is the GraphQL query we need to return data back from the source Markdown files used to create the posts for this blog:
    export const pageQuery = graphql`
      query BlogPostByPath($path: String!) {
        markdownRemark(frontmatter: { path: { eq: $path } }) {
          html
           frontmatter {
             date(formatString: "MMMM DD, YYYY")
             path
             title
             author
           }
         }
       }
    `;
     
  4. 4.

    Go ahead and save the file and then close it. The main source files are now in place; we will bring it all together in the next exercise.

     

The exercise we have just completed may have been more straightforward, but it still plays a critical role in displaying blog content – its part will become apparent very shortly. It exposes a few key points that are worth understanding in more detail, so let’s break apart the code we’ve just added and explore it in greater detail.

Understanding the Changes Made

In comparison to other exercises we’ve completed thus far, this was probably one of the shortest, yet that doesn’t belie the usefulness of this demo! For this demo we’ve just worked through, we created a template component to help render the content generated from the Markdown source files into something we can view on-screen.

We started by importing the usual suspects, such as React and react-helmet (the latter used to change the title shown in the browser window). We then created a variable post to store the data retrieved from data.markdownRemark, using the GraphQL query at the foot of the component. Once retrieved, we iterate through it to display the content in the relevant field on-screen.

Tying It All Together

With all of the code files in place, we now have one last step, which is to bring it all together. For this, we will use a similar process to one we’ve already implemented for the product pages, where we used createPages() to generate the pages dynamically during compilation.

It is at this point where things will get a little trickier, as we have to combine two GraphQL queries into one but make sure we only call the right one at the right time! We should also bear in mind that this method does have a few drawbacks – we covered many of these earlier in the book. For now, though, let’s go ahead and modify the gatsby-node.js file to create the blog posts when we compile our site.

UPDATING THE GATSBY-NODE.JS FILE
We have a few steps to implement to update the gatsby-node.js file, so let’s make a start:
  1. 1.

    First, go ahead and open the file in your text editor – it’s at the root of the project folder.

     
  2. 2.
    Look for this line, const { createPage } = actions, then leave a line blank under it, and then add in this const value:
      const blogPostTemplate = path.resolve(`src/templates/blog-template.js`);
     
  3. 3.
    A little further down, you will see this line of code: allShopifyProduct {. Modify this line as indicated:
    {
      shopify: allShopifyProduct {
        edges {
     
  4. 4.
    Immediately below this block
              node {
                handle
              }
            }
          }
     
…add in this GraphQL query:
blog: allMarkdownRemark( sort: { order: DESC, fields: [frontmatter___date] }
        limit: 1000
      ) {
        edges {
          node {
            excerpt(pruneLength: 250)
            html
            id
            frontmatter {
              date
              path
              title
              author
            }
          }
        }
      }
The following code extract shows how the GraphQL query should slot into our code:
return graphql(`
  {
    shopify: allShopifyProduct {
      edges {
        node {
          handle {
        }
      }
  }
  blog: allMarkdownRemark(
    sort: { order: DESC, fields: [frontmatter__date]     }
    limit: 1000
) {
    edges {
  1. 5.

    Scroll down toward the bottom of the page, and look for the line starting result.data.allShopifyProduct. Replace the word allShopifyProduct with shopify, as indicated:

     
result.data.shopify.edges.forEach(({ node }) => {
  1. 6.
    Next, look for the closing brackets of the result.data… block. Leave a blank line, and then add in this:
        result.data.blog.edges.forEach(({ node }) => {
          createPage({
            path: `${node.frontmatter.path}`,
            component: blogPostTemplate,
            context: {}, // additional data can be passed via context
          });
        });
     
  2. 7.
    As the last step, add in this Promise.reject block, immediately below the line if (result.errors) {, which is after the end of the GraphQL query:
        if (result.errors) {
          return Promise.reject(result.errors);
        }
     
  3. 8.

    Go ahead and save the file – you can close it, as changes are now complete for this file.

     

The gatsby-node.js file can be tricky to work with; if we don’t add in the GraphQL query correctly, then we might find some odd errors appearing. Blog posts may be listed, but clicking through to them doesn’t operate, for example! We’ve covered some useful tricks in this last exercise, so let’s pause for a moment to review the changes we’ve made to the gatsby-node.js file for our blog.

Exploring the Changes

This last exercise was the most critical to get right – it is where we dynamically generate each of the blog posts, using a similar process to that which we did for the product pages earlier in this book.

We started by adding in a variable blogPostTemplate to store the location of the template file used to create the blog posts, before tweaking the GraphQL queries used by Shopify and what will be our blog. The core queries themselves didn’t change; we added a tag to help identify them when Gatsby runs the queries during the processing stage.

Next up came the addition of a new .forEach block to iterate through each source Markdown file and send the relevant fields for rendering in the blog template. We then rounded it out by adding a Promise.reject block to show any errors should the process fail during compilation.

It’s important to note that we built this process into a promise block; this prevents Gatsby from trying to create the pages if the initial GraphQL queries return errors or no content.

Okay, let’s crack on: we now have the basics of our blog in place, so the next task is to see how it runs! Before we do that, though, we need to add in a handful of additional style rules so that content is at least presentable on-screen! This change is a quick task to complete, so let’s dive in and take a look.

Styling the Blog Pages

This next section is one where we could go to town with adding styles – yet, we’re only going to add a handful! What gives?

Well, the simple answer is that there is nothing special about adding styles to a Gatsby project; we’ve already set up a style sheet in the form of global.scss that uses Sass to process the rules into valid CSS styles.

Once we’ve added in enough to give us a good grounding, we can then apply different styles in the same way – that is something I will leave for you to do later as a challenge! Bringing things back to reality, let’s quickly dive in and add the necessary styles to reformat the content on our page.

STYLING THE BLOG
We won’t go into adding lots of styling in this demo, but enough to complement what is already present in each component and on the blog.js page and template:
  1. 1.
    We’ll start by cracking open the global.scss file in the srcstyles folder – scroll to the bottom of the file, and then add in this code:
    .published { font-size: 14px; font-style: italic; }
    .blog-post-preview h2, .blog-post h3 { margin-bottom: 0; }
    .blog-post-preview h2 a { text-decoration: none; }
    .blog-post-preview h2 a:hover { text-decoration: underline; }
    .blog-post-preview p, .blog-post p { margin-top: 15px; }
     
  2. 2.

    Save the file – that’s all. Sorry if you were expecting more code! You can close the file – we no longer need it for this exercise.

     
  3. 3.

    The last step is to preview the results of our work – for this, revert to or fire up a Node.js terminal session, and change the working folder to our project area.

     
  4. 4.

    At the prompt, enter gatsby develop and press Enter. Gatsby will go away and load the development server – when prompted, you can view the site at http://localhost:8000. Try clicking the blog link in the navigation; if all is well, we should have something akin to this screenshot (Figure 7-2).

     
../images/499924_1_En_7_Chapter/499924_1_En_7_Fig2_HTML.jpg
Figure 7-2

Our (unstyled) blog summary list

Excellent, we now have all of the basics in place; this last exercise was a quick one, to add in the final styles needed to make our content look at least presentable. At the same time, we did a quick check to see how it looked in a browser; we could have used Netlify, but the command gatsby develop is sufficient for us. The styles are local, and there is no need to satisfy conditions such as testing in a secure environment (as we might have otherwise needed with Netlify!)

Let’s move on: the next stage is to explore how we can add content to our blog. This is something we’ve already (in part) done. It’s a good point, though, to review how we should do this in a little more detail to help understand the journey from Markdown source files through to valid posts in our blog.

Adding Content to the Blog

So far, we’ve focused on the technical means of getting our blog pages to appear – what about writing the content? This book isn’t about the ins and outs of writing Markdown, but it’s still worth spending a few moments to review how the example files were prepared at a very high level. Let’s use the second-post as an example, as this has several useful Markdown fields within it.
../images/499924_1_En_7_Chapter/499924_1_En_7_Fig3_HTML.jpg
Figure 7-3

Example headings from a Markdown source file

Here, we’ve specified five in total, namely, the source path, date, title, author, and main header (or featured) image. These are all enclosed in two dividing lines made up of three hyphens – as long as we follow this format for each Markdown file, then it stands a chance of being processed into a valid blog post for our site.

In this example, we can reference all of these fields in React using the format post.frontmatter.XXXXX, where frontmatter is the content in the markdown header and XXXXX represents the field you want to retrieve, such as post.frontmatter.title for the title. As soon as we save the Markdown file into the blog folder, it is processed – you will see the summary appear in the blog listing on our site.

The only provision is that if we add in additional fields, we must include these as fields in the queries within blog.js, gatsby-config.js, and blog-template.js. Otherwise, we will see errors where GraphQL tries to query nonexistent fields!

If you would like to learn more about how to format text for Markdown, then I would refer to a site such as the Markdown Cheat Sheet, available at www.markdownguide.org/cheat-sheet.

Adding content is just part of the picture, though. As everyone knows, pictures speak a thousand words; we need to add some visual content in too! It is straightforward to do; let’s take a look at the steps involved in more detail.

Adding Images to the Blog

Take another look at one of the front matter blocks in our demo Markdown files – noticed the use of featuredImage entries there?

You may have also noticed that when we updated the code on Netlify, only some of these images were coming through; in-line ones would be OK, but not the featuredImage ones.

Fortunately, this is easy to fix: we need to amend the GraphQL queries in use in three files. Before we work on that, let’s quickly cover off how we import images from the body of the text into our blog pages. Deep in the Markdown of second-post, we have this in-line image command:
![Hopper The Rabbit](../assets/gatsby.png)
When adding images, we need to use the format ![name of the image, used as alt tag](physical location of the image, as a relative URL). We then use this configuration option to render the images:
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 800,
            },
          },
        ],
      },
    },
We use the gatsby-transformer-remark plugin to render the Markdown, while gatsby-remark (passed in as an option) turns image markdown into real images. This latter plugin does three things:
  • Adds an elastic container to hold the image, preventing layout jumping

  • Creates multiple versions of images at different sizes – it uses srcset and image sizes to load the correct image, depending on the size of the browser window/platform

  • Blurs up the image on the initial load with a small 20 px wide image used as a placeholder until the browser downloads the real image

Okay, theory aside. Let’s crack on with updating our code to complete the image support for our blog.

FINISHING SUPPORT FOR FEATURED IMAGES
To complete the image support, work through these steps:
  1. 1.
    First, open up a copy of blog.js in your text editor, and then look for the author entry in the GraphQL query toward the bottom of the page:
                date(formatString: "MMMM DD, YYYY")
                path
            author
     
  2. 2.
    Immediately below it, insert this entry:
         featuredImage {
           childImageSharp {
             fluid(maxWidth: 960) {
               src
               srcSet
               aspectRatio
               sizes
               base64
             }
           }
         }
     
  3. 3.
    It should look something akin to this code extract:
         author
         featuredImage {
           childImageSharp {
             fluid(maxWidth: 960) {
               src
               srcSet
               aspectRatio
               sizes
               base64
             }
           }
         }
     
  4. 4.

    Save the file and close it – the change is complete for this file.

     
  5. 5.

    We also need to update gatsby-node.js; go ahead and repeat steps 1–4, remembering to save the file once we complete the changes.

     
  6. 6.

    We have a couple more changes to make in blog-template.js. Crack this open in your text editor, and then add in this line immediately below the one beginning with <span className=" published"...>:

     
<Img fluid={featuredImgFluid} />
  1. 7.

    We also need to import the Gatsby Image plugin, so go ahead and add this line in, immediately below the last import statement at the top of your file:

     
import Img from "gatsby-image"
  1. 8.

    Go ahead and save and close any files open – the changes are now complete.

     

At this point, you can either update the code on Netlify (see the previous exercise) or rerun gatsby develop at the command line; either will show the updated content. It’s essential to rerun gatsby develop (or gatsby build), as we’ve edited the gatsby-node.js file; any changes made to it do not take effect until either process is rerun.

This particular exercise is something of a double-edged sword; adding several fields to a GraphQL should be easy enough, but it can easily trip us up if we don’t get the brackets in the right place!

In this instance, the changes we made were small; it involved merely adding in the featuredImage reference. It is an object reference, so we needed to include fluid (to make the image responsive), as well as details such as the src location, aspectRatio, and sizes values. A great way to help make sure your code is correct is to use the GraphiQL editor at http://localhost:8000/__graphiql; the Prettify function will soon tell you if the code isn’t right!

Refining Our Blog: Taking Things Further

We are almost at the end of this chapter on creating a blog for our site, but I want to leave you with hopefully an answer to at least one question I am sure you will ask at some point: where do we go from here?

It’s a great question – to which I could give you a short answer, “The world is your oyster!” For those of you not familiar with that saying, it translates as being you are only limited by your imagination. Yes, it might sound like a cop-out, but that is not what I intended! It is up to you how you want to proceed – to give you a starter, here are a few ideas to whet your appetite:
  • We’ve included some basic styles to make the page look a little more presentable, but what about taking this further? After all, you don’t want your blog to look dull, so anything to give it visual impact will be of benefit. You could easily update the individual components to use CSS-in-JS-based styling, but I would start by using classic CSS and tagging it onto the end of the global.scss file. Sure, it’s not Sass, but that doesn’t matter for now: as long as it is syntactically correct, Sass will still compile it into valid CSS.

  • What about adding SEO measures? SEO is, of course, essential for the survival of your blog (and site), so adding it is a must. You could make use of the SEO component that comes with most Gatsby starter themes as a starting point and then develop it further once you get it established.

  • Any blog worth its salt should have a short bio for the author; I’ve added in something as a placeholder, but what about adding an image and making the content a little more dynamic? For our example, it would be better to put it in the DatoCMS setup, or potentially the native GraphQL that comes with Gatsby, rather than Markdown – it keeps the content separate.

  • A feature we’ve not added in is next or previous links or a back to homepage link for that matter – check out the article on Medium by Aman Mittal, at https://medium.com/crowdbotics/how-to-build-your-own-blog-from-scratch-with-gatsbyjs-graphql-react-and-markdown-78352c367bd1 for an example you could adapt for your purposes.

  • Although we’ve created our blog from scratch, there are two or three components available in a Gatsby starter theme at https://github.com/gatsbyjs/gatsby/tree/master/starters/blog/src/components – it might be worth trying these out.

  • We’ve focused on just rendering content from our blogs on-screen, but what about really going to town and starting to mix in content from Shopify too? Granted, it’s not the easiest to manipulate, but you can at least add in links and images to products, so the pages have content that provides a call to action within the pages.

These are just a few ideas to help get you started and give you something to consider adding to your blog; Gatsby is infinitely versatile, so it is up to you (and your customer’s requirements) as to where you want to take your social media presence!

Summary

One of the great things about Gatsby is that it was written using React; this makes it so versatile as it can harness the power of one of the world’s most familiar tools. It is no more valid than with creating blogs; although we’ve only touched the surface of what is possible, we can use this as a basis for developing something more refined for production use. Before we get to that stage, though, let’s take a moment to review what we’ve covered thus far in this chapter.

We began by setting the scene with a quick look at how we would build our blog, as well as previewing how the final article would look. We then moved on to installing the requisite plugins before turning our attention to updating the existing blog.js file to form the basis for our new blog.

Next up, we added in the blog template to display our content on-screen, before tying it all together with changes to the gatsby-node and gatsby-config files. We then rounded out the chapter with a look at how we added in images and content, before exploring some ideas to help you develop the blog into something more suitable for production use.

Phew, we come to the end of another intensive chapter, but certainly not the end of the book! We have the basics all in place. “So what’s next?” I hear you ask. Well, now’s an excellent time to refine what we have and add in missing features, such as localization, SEO support, and the like. There are plenty of finishing touches we can add to our site as a whole – stay with me, and we work through a few of them in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.141