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

Use Gatsby's File System Route API to Generate Pages for Each MDX File

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years ago

In the pages directory, create the {Mdx.slug}.js file. Using curly braces, you can denote a file system route API that operates on all "Mdx" nodes and creates a page with the path slug available on that node.

The File System Route API automatically passes the id of each MDX file node to the GraphQL query inside this file. Use the id to filter the query and get access to the processed MDX file.

Finally, pull in data, the result of our query, and expose the title from the frontmatter.

Instructor: [0:00] In your pages directory, use curly braces to create a file called mdx.slug.js. This is telling Gatsby to create a page for every mdx file in your project using the built-in slug, which is derived from the file name of the mdx file. Inside this pages file, we're going to create a new component which will be used to render each of the pages for each of the mdx files.

[0:36] We're going to grab { graphql } from 'gatsby'. When you create a file using the File System Route API, it lets you create a component as well as a query.

[0:51] The query uses the GraphQL template function. The File System Route API automatically passes the id of each of the mdx file nodes to this component. We'll represent that by $id. That means we can use that id to filter. We'll grab the mdx file node with the =id. Now we have access to that mdx file.

[1:49] For now, we'll grab the title from the frontmatter. We'll return it as an h1 tag, so that we're adhering to Semantic HTML. First, we need to pull in data, which is the result of our query, access mdx frontmatter title. Now we can navigate to /learning-gatsby and we should see our title rendered.

[2:26] If we add another post, egghead.mdx, we should be able to navigate to /egghead, showing that we're creating a page for each mdx file.

Hector
Hector
~ 3 years ago

Hi there! Instructive and clear course, thank you! Just wanted to say, for those of us that are very new to graphql and/or gatsby (presumably a good few), it might be interesting to hear more about how the query runs and passes data to our component (or link to documentation to that effect).

Laurie Barth
Laurie Barthinstructor
~ 3 years ago

You're absolutely right! The docs are available here but I'll be sure to add them to the lesson as well.

Hector
Hector
~ 3 years ago

Thank you again -- awesome course, really grateful! Been an great way to test the waters with both graphql & gatsby & I'm starting to see why they've gotten so popular :)

Markdown supported.
Become a member to join the discussionEnroll Today