Add a List of Posts using a GraphQL Page Query

Laurie Barth
InstructorLaurie Barth

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

Inside of index.js, create a page query that grabs allMDX nodes, and in each node, grab the slug and title, that's available via the frontmatter.

Additionally, create a filter to sort all results using the frontmatter title field. Map through each post using the result of the query in the data object.

Finally, use the Link component and the slugs provided by the query result to link to each post.

Instructor: [0:04] Import the graphql template tag from Gatsby. We're going to make a page query that will grab all the information we plan to render on this page. The query will grab all MDX nodes. In each node, we want to grab the slug and the title that's available inside the frontmatter.

[0:40] We also want to add a filter to this query. We're going to sort all results using the frontmatter title field. We want to sort them in ascending order, which will be alphabetical. Now we have access to the results of this query on the data object. We'll make a little shortcut to the available posts, data.allMdx.nodes.

[1:33] We'll map through each of the posts in order to display the information we want. We'll start by putting the title in an h2. Now we can see the title for each of our posts.

[2:25] We'll grab the link component from Gatsby, and now we can use it to navigate to each of the posts, using the slug that we've queried. We'll also add a key so that there is a unique identifier for each of the elements rendered inside our map.

[3:01] Now we can navigate to each of our posts from the home screen.