
Dynamically Create Pages in GatsbyJS (v2)
GatbsyJS is a super powerful and blazing fast static site generator built on React. One of the greatest inventions was the createPages API GatsbyJS offers. This tutorial will assume previous knowledge of how to create and run a GatsbyJS project.
This brief tutorial will show you how you can use the createPages API and highlight how useful it can be.
Firstly, you need some GraphQL data to create the pages with. For this tutorial, we will use some data from Wordpress. Click here if you want to read about how to pull data into GatsbyJS from a Wordpress website.
{
allWordpressPost {
edges {
node {
id
title
date(formatString: “MMMM DD, YYYY”)
}
}
}
}Above is some data we will use to create our pages.
Open up your gatsby-node.js file (or create one if you don't have one in your root directory). Before we can write any code we must require four packages.
const _ = require('lodash');
const Promise = require('bluebird');
const path = require('path');
const slash = require('slash');Below is the code needed to dynamically create the pages from your GraphQL data.
exports.createPages = ({ graphql, actions}) => {
const { createPage } = actions;
return new Promise((resolve, reject) => {
graphql(`{
allWordpressWpProject {
edges {
node {
slug
title
id
}
}
}
}`
).then(result => {
if (result.errors) {
console.log("createPages Error :'(")
console.log(result.errors);
reject(result.errors);
}
const postTemplate = path.resolve("./src/templates/projectItem.js");
_.each(result.data.allWordpressWpProject.edges, edge => {
createPage({
path: `/projects/${edge.node.slug}/`,
component: slash(postTemplate),
context: {
allPostData: edge.node,
},
});
});
resolve();
});
});
};