Gatsby Pages

Post 2Jun 2020

With the learning of Gatsby, I felt its powerful functionalities in creating pages, handling images and data implementation with Graphql. It saves a huge amount of time for front end developers in building sites and accelerate the process of deploy. With the React framework as the basic structure, and thousands of plugins, Gatsby is not just for building static sites, it can be used to build many web apps that used React to develop today with a better performance.

Here are process of how to auto generate pages based on slugs you created, it bothers me for a while for understanding how it works, I am writing here for people who may encounter into the same problem and for myself for the future reference.

In the building of a blog site or any other sites relate to redirect to the pages that show different information in a same template, we will not create every single page out in the directory, we need a more elegant solution for example based on the title of the page or the slug of the page, these pages will be auto generated and we just need to redirect to the page based on the slug or title we provide.

In order to achieve this, in Gatsby we should prepare four things: get your content’s slug, title, create a template page, setup the Gatsby-node.js file to create pages based on these slugs, titles or ids and point to the template page, then get the content data based on these attributes on your template page. I will show the example that I practiced based on info I setup in Contentful with Gatsby.

First of all, I generate a Graphql query that only shows my blog’s slugs, where slug property is within the data structure of my blog’s contents, titles and other properties.

query MyQuery { 
     posts: allContentfulPosts { 
       nodes { 
         slug 
       } 
     } 
 }

In the Gatsby-node.js, fetch the slug data and auto generated pages based on these slugs, point these pages with the template page we created.

alt-text

Our templates will look like:

alt-text

You can log out the props to check if the slug we point from node file is in our template page now.

Based on the data structure you have, create a query with the slug argument to get the specific contents.

alt-text

That’s it! Happy coding 🙂