⚠️ This lesson is retired and might contain outdated information.

Create Static Pages Programmatically

Khaled Garbaya
InstructorKhaled Garbaya
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 years ago

To create a page programmatically you need to a few things.

1. Create a template file

under src create a folder called templates and inside of that create a file called pokemon.js.

2. Use the Gatsby createPage node API

in the root of the project create a gatsby-node.js file and add the following code

const path = require(`path`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  const templatePath = path.resolve(
    './src/templates/pokemon.js'
  )

  // use the createPage function to create a page.
  // the createPage function accepts an object as a config
  // {
  //   path: // the path to the page, we want it to be `/user`
  //   component: // the path to the component file
  // }
}

Instructor: [0:00] Let's go to our project. Inside of src, let's create a new folder. Call it templates. Inside of templates, let's create a new file. Call it pokemon. Here, we'll import React and export a component.

[0:22] The route of the project, let's create a new file. Call it gatsby-node.js. Let's require the path utility from node, and export a function. Export the function called createPages(). We'll get the argument actions to create a page.

[0:44] Programmatically, we need to extract the createPages()from actions. Let's get the path for our template using the path.resolve. Now, let's create a page. First thing, we need to pass the path. Here, we will have /pokemon for the component. We will pass the pokemon template. Hit save.

[1:10] Let's run our server. Let's go to /pokemon. Hit enter. Then you can see here we can see our page. You can also pass some arguments to the page to render. To do that, we can use the context object. Here, for example, let's pass in a name like Pikachu. Save this as go-to the Pokémons template.

[1:48] Then here, we'll get the pageContext. We can render the name here, pageContext name, and hit save. You can see here the Pikachu is showing in that page.