Alt Text

Welcome to part-8 of the series. Now, it’s time to generate those pages programatically, when we click on the Read More button.

First create a file post-template.js file inside the templates folder. Let’s do all the necessary imports required in it first.

post-template.jspost-template.js

We will next create a simple query in graphql playground to get all the slugs.

slug queryslug query

Now, to create pages dynamically we have to create a file gatsby-node.js in the root directory.

Here, we are having a NodeJS file so the syntax is according to that. We are first using the query which we had created above.

After that we are receiving the posts. We are looping through it and creating page through the post-template.js file which we had created.

gatsby-node.jsgatsby-node.js

We need to then close the gatsby develop and re-run it, but i was getting error as i didn’t have any postTemplate.module.css in the css folder. Let’s quickly create an empty file.

postTemplate.module.csspostTemplate.module.css

After restarting gatsby develop head over to any non-existent page in the browser and you can see the dynamically created page.

Dynamic pagesDynamic pages

If we click any one of them, we will get the matter from post-template.js file.

postTemplatepostTemplate

Now, we will first write the GraphQL query to get the single post. Here, we are using mdx and passing a slug to it. In the playground we are using Query Variables to pass a slug.

Single PostSingle Post

This completes part-8 of the series.

You can find the code for the same in this github repo.

This post is also available on DEV.