Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Programmatically create Gatsby pages from Contentful data

    Khaled GarbayaKhaled Garbaya
    gatsbyGatsby
    ^2.5.7

    In this lesson, you will learn how to create pages dynamically in Gatsby based on data coming from Contentful

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: Here, I have my Gatsby website, and it's listing all the lessons that are coming from Contentful. If we click in one of the lessons, you can see here, Gatsby is giving us a 404 page. That's because we need to create a page for every lesson to show its details.

    To do that, we need to go to the Gatsby Node.js and write some code here to create the pages. First, we need to export a createPages function. We can then extract the createPage from the actions object. To be able to create a page, we need a path to a template, which is basically a React component.

    We will create the lesson.js later. Let's import path in here. Now, we can use GraphQL to query the Gatsby data for all the Contentful lessons.

    The GraphQL function returns a promise that will contain our result, and inside of the result, we need to check for errors. If so, we throw the error. Otherwise, we can create our pages. To do that, we need to loop through all the edges and create a page for every lesson.

    The createPage will accept the path the component, and a context for additional data. Let's save this and create our lesson template. Let's go to SRC and create a new folder. Call it templates. Inside of templates, we need to create a file called lesson.js.

    Let's do some imports first. We need React, we need GraphQL from Gatsby, we need the layout component, and the SEO component. Before we render anything, we need to get some additional data for the lesson detail.

    We need to export a GraphQL query. This will get the lesson query and use the slug that we passed in the component context when you create the page, and get all the data that we need. Once the query is successful, we will get this data object that has all the data, so we can fill in our components.

    Finally, let's export the lesson component. Let's hit save, and we need to restart our server. Now, if we refresh, go to the one of the lessons, and scroll down, you can see here the title of our lesson. If we check the second one, indeed, we can see its title.