List out all categories and count the number of posts in Gatsby

ReactJS|OCTOBER 3, 2024|1 VIEWS
To list out all categories and count the number of posts in each category using a GraphQL query in Gatsby, you can use the allMdx query to group the posts by category and count the number of posts in each group.

Here’s how you can do it:

GraphQL Query

Example your mdx content

categories: ["ReactJS"]

Add the following GraphQL query to your component to fetch the categories and their post counts.

query {
  categories: allMdx {
    group(field: frontmatter___categories) {
      fieldValue
      totalCount
    }
  }
}

Display Categories and Counts

import * as React from "react";
import { graphql } from "gatsby";

const IndexPage = ({ data }: any) => {
  return (
    <div>
      <div className="pb-8 px-4">
        <div className="flex flex-wrap justify-center gap-6">
          {data.categories.group.map((category: any) => (
            <div key={category.fieldValue}>
              <a className="text-red-500 font-semibold uppercase text-lg">
                {category.fieldValue} ({category.totalCount})
              </a>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export const query = graphql`
  query {
    categories: allMdx {
      group(field: frontmatter___categories) {
        fieldValue
        totalCount
      }
    }
  }
`;

export default IndexPage;