Add Tags & Categories to Gatsby MDX blogUpdated: September 10, 2020
Tags and categories are an important section of a website, since they provide an easy way for visitors to browse content on your platform.
To add tags to your Gatsby MDX blog posts, you need to have your site set up to convert MDX files into blog posts.
Add tags to your MDX files
You can add tags in the
frontmatter of your MDX file:
frontmatter is the top area of your Markdown or MDX file that is surrounded by dashes.
It includes the title of your post, a date and any other field that is a string, number, or array.
Considering that posts can have multiple tags, I have defined the above tag field as an array.
Write a query to get all tags for your posts
Now that the
tags fields are available in the data layer, we can use
graphql to query it.
Try running the following query, which groups posts by
tags, locally in your GraphiQL
Then, modify your
gatsby-node.js file with the above query:
Make a tags page template
As you can see on the
gatsby-node.js file, we need a tag page template in order to generate individual pages for the tags in your posts.
Let's create a tag template for
Make a tags index page
Finally, once we've generated pages for every tag, it's time to create a tags index page.
This page will render a list of all tags (
src/pages/tags.js), followed by the number of posts with that particular tag.